在列表中搜索数字

时间:2015-11-09 02:40:34

标签: python

我有一个列表,数据分成字符串,列表如下所示

['Equifax', 'BUY', 'Icelandic', 'Krona:', '41983']

我想将其拆分,以便每个值都有不同的变量,因此我使用了以下代码

    yourlist = line.split()
    company=yourlist[0]
    action=yourlist[1]

我的问题是我需要将货币设置为等于行动之后和列表中最终值之前的所有货币,以便冰岛和克朗成为货币。那么如何将ammount设置为列表的最后一个元素,然后currentn等于action和ammount之间的所有内容?

1 个答案:

答案 0 :(得分:2)

您需要列表slicing

l = ['Equifax', 'BUY', 'Icelandic', 'Krona:', '41983'] 
# l is a list, no need for split()

company = l[0]

action = l[1]

currency = l[2:-1]
# the previous lines sliced the list starting at the 3rd element
# stopping, but not including, at the last item

amount=l[-1]
# counting backwards [-1] indicates last item in a list.

company
Out[22]: 'Equifax'

action
Out[23]: 'BUY'

currency
Out[24]: ['Icelandic', 'Krona:']

amount
Out[25]: '41983'