在列表中搜索一个麻木的

2024-06-16 10:13:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我想把它分开,这样每个值都有一个不同的变量,所以我使用了下面的代码

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

我的问题是,我需要设置货币等于一切行动后,在清单中的最终值之前,所以冰岛和克朗将是货币。那么,如何将ammont设置为列表的最后一个元素,然后curreny等于action和ammont之间的所有值呢


Tags: 数据字符串代码列表line货币actionbuy
1条回答
网友
1楼 · 发布于 2024-06-16 10:13:53

您需要列表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'

相关问题 更多 >