从列表中提取某些元素

时间:2010-08-20 07:57:59

标签: python join

我对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 }'类似。我怎么能做到这一点?

第二次

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

7 个答案:

答案 0 :(得分:5)

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

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

print ','.join (line[0:2])

A,B

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

A,B

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而不是切片,但它是另一个子流。这就是我在第二个连接示例中使用的内容。

答案 1 :(得分:2)

您不希望使用join。如果您只想打印列表的某些位,请直接指定所需的位:

print '%s %s %s %s' % (line[0], line[1], line[4], line[6])

答案 2 :(得分:2)

假设line变量应该包含一行单元格,用逗号分隔......

您可以使用map

line = "1,2,3,4,5,6"
cells = line.split(",")
indices=[0,1,4,6]
selected_elements = map( lambda i: cells[i], indices )
print ",".join(selected_elements)

map函数将为list参数中的每个索引执行on-the-fly函数。 (根据自己的喜好重新排序)

答案 3 :(得分:2)

您可以使用以下列表理解:

indices = [0,1,4,6]
Ipadd = string.join([line[i] for i in xrange(len(line)) if i in indices])

注意:您也可以使用:

Ipadd = string.join([line[i] for i in indices])

但是你需要一个排序的索引列表而不会重复。

答案 4 :(得分:1)

回答第二个问题:

如果您的字符串包含在myLine中,请执行以下操作:

myLline = myLine[:-1]

删除最后一个字符。

或者你也可以使用rstrip()

myLine = myLine.rstrip("'")

答案 5 :(得分:1)

l = []
l.extend(line[0:2])
l.append(line[5]) # fourth field
l.append(line[7]) # sixth field
string.join(l)

可选地

"{l[0]} {l[1]} {l[4]} {l[5]}".format(l=line)

see PEP 3101并停止使用%运算符进行字符串格式化。

答案 6 :(得分:1)

>>> token = ':'
>>> s = '1:2:3:4:5:6:7:8:9:10'
>>> sp = s.split(token)
>>> token.join(filter(bool, map(lambda i: i in [0,2,4,6] and sp[i] or False, range(len(sp)))))
'1:3:5:7'
相关问题