Skip to main content
 首页 » 编程设计

python之从列表中提取某些元素

2025年05月04日8freeliver54

我对 Python 一无所知,开始在一些文件上使用它。除了两件事之外,我设法找到了如何做我需要做的所有事情。

第一名

>>>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 

我希望它的工作方式类似于 awk '{ print $1 $2 $5 $7 }'。我怎样才能做到这一点?

第二

如何删除该行的最后一个字符?我不需要额外的 '。

请您参考如下方法:

假设此处的连接只是为了打印或存储一个漂亮的字符串作为结果(使用逗号作为分隔符,在 OP 示例中它本来可以是字符串中的任何内容)。

line = ['A', 'B', 'C', 'D', 'E', 'F', 'G'] 
 
print ','.join (line[0:2]) 

甲乙

print ','.join (line[i] for i in [0,1,2,4,5,6]) 

A,B,C,E,F,G

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

print ','.join ([line[0], line[1]]) 

甲乙

print ','.join ([line[0], line[1], line[2], line[4], line[5], line[6]]) 

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 

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