从列表中提取某些元素

1 python join

我对Python没有任何线索,并开始在某些文件上使用它.我设法找到了如何做我需要的所有东西,除了两件事.

1

>>>line = ['0', '1', '2', '3', '4', '5', '6']
>>>#prints all elements of line as expected
>>>print string.join(line)
0 1 2 3 4 5 6

>>>#prints the first two elements as expected
>>>print string.join(line[0:2])
0 1

>>>#expected to print the first, second, fourth and sixth element;
>>>#Raises an exception instead
>>>print string.join(line[0:2:4:6])
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

我希望这个工作类似于awk '{ print $1 $2 $5 $7 }'.我怎么能做到这一点?

第2

如何删除该行的最后一个字符?还有一个'我不需要的东西.

kri*_*iss 5

如果这里的连接只是为了打印或存储一个很好的字符串作为结果(使用昏迷作为分隔符,在OP示例中它将是字符串中的任何内容).

line = ['A', 'B', 'C', 'D', 'E', 'F', 'G']

print ','.join (line[0:2])
Run Code Online (Sandbox Code Playgroud)

A,B

print ','.join (line[i] for i in [0,1,2,4,5,6])
Run Code Online (Sandbox Code Playgroud)

A,B,C,E,F,G

在这两种情况下,您正在做的是从初始列表中提取子列表.第一个使用切片,第二个使用列表理解.正如其他人所说,你也可以逐个访问元素,上面的语法只是简写:

print ','.join ([line[0], line[1]])
Run Code Online (Sandbox Code Playgroud)

A,B

print ','.join ([line[0], line[1], line[2], line[4], line[5], line[6]])
Run Code Online (Sandbox Code Playgroud)

A,B,C,E,F,G

我相信列表切片上的一些简短教程可能会有所帮助:

  • l[x:y]是列表l的"切片".它将获得位置x(包括)和位置y(排除)之间的所有元素.位置从0开始.如果y不在列表中或缺失,它将包括所有列表直到结束.如果您使用负数,则从列表末尾开始计算.您还可以使用第三个参数,l[x:y:step]如果您想要定期间隔"跳过"某些项目(不要将它们放入切片中).

一些例子:

l = range(1, 100) # create a list of 99 integers from 1 to 99
l[:]    # resulting slice is a copy of the list
l[0:]   # another way to get a copy of the list
l[0:99] # as we know the number of items, we could also do that
l[0:0]  # a new empty list (remember y is excluded]
l[0:1]  # a new list that contains only the first item of the old list
l[0:2]  # a new list that contains only the first two items of the old list
l[0:-1] # a new list that contains all the items of the old list, except the last
l[0:len(l)-1] # same as above but less clear 
l[0:-2] # a new list that contains all the items of the old list, except the last two
l[0:len(l)-2] # same as above but less clear
l[1:-1] # a new list with first and last item of the original list removed
l[-2:] # a list that contains the last two items of the original list
l[0::2] # odd numbers
l[1::2] # even numbers
l[2::3] # multiples of 3
Run Code Online (Sandbox Code Playgroud)

如果获取项目的规则更复杂,您将使用列表推导而不是切片,但它是另一个子流.这就是我在第二个连接示例中使用的内容.