在数组中只拆分或提取整数 - Python

2024-04-25 02:12:54 发布

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

我的搜索技能需要提高,因为我找不到(或理解)任何可能对我有帮助的东西,从这个数组中。。。你知道吗

qtyList = ['[40', '68]', '[18', '10]']

我试着只提取整数和/或把它放在一个不同的数组中,这样看起来像。。。你知道吗

qtyList = [40, 68, 18, 10]

我以为stru-split可能有用,但我很确定我弄错了语法。我试过。。。你知道吗

array str_split($qtyList, "[")

那没用。你知道吗


Tags: 技能语法整数数组arraysplitstrstru
3条回答

使用list comp和regexp是一种方法:

>>> qtyList = ['[40', '68]', '[18', '10]']
>>> import re
>>> [int(re.search('\d+', el).group()) for el in qtyList]
[40, 68, 18, 10]

下面是一种遍历列表中每个列表项的方法。你知道吗

for item in qtyList:
    for x in item:
        newList.append(x)
In [1]: qtyList = ['[40', '68]', '[18', '10]']

单向:

In [2]: [int(s.replace('[', '').replace(']', '')) for s in qtyList]
Out[2]: [40, 68, 18, 10]

另一种方式:

In [3]: import re

In [4]: [int(re.sub('[\[\]]', '', s)) for s in qtyList]
Out[4]: [40, 68, 18, 10]

这里有一个奇怪的方法,如果列表总是像你展示的那样交替出现:

In [5]: from itertools import cycle

In [6]: slices = cycle((slice(1, None), slice(None, -1)))

In [7]: [int(s[c]) for s, c in zip(qtyList, slices)]
Out[7]: [40, 68, 18, 10]

相关问题 更多 >