开发者

Make a list out of variables

This is part of my sc开发者_StackOverflow社区ript:

for line in range(0,len(lines),2):
        num = lines[line].split()[8]
        num1= abs(num)

Obviously I can produce many num1 here from each line....

Here I want to put all these num1 into one list, then how can I do? thx

Sorry guys, this is python! lol


li = []
for line in range(0,len(lines),2):
        num = lines[line].split()[8]
        li.append(abs(num))

or

li = [abs(lines[line].split()[8]) for line in range(0,len(lines),2)]


In Python, we iterate directly. You want items from the list of lines, so ask for items of the list of lines. Don't ask for numeric indices and then index into the list.

Since we want every other line, the simplest way to do that is to just 'slice' the list.

We can build up the list of results by using a list comprehension. Don't waste your breath telling Python how to put things together into a list. Just tell it what should be included.

Oh, and as noted, the list contains strings, and chopping it up produces more strings, and we can't apply abs to a string. We need to convert the result explicitly first.

result = [abs(int(line.split()[8])) for line in lines[::2]]


newlist.add(num1)

What language are you trying to do this in?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜