如何在Python中过滤/清理列表

2024-09-26 22:11:17 发布

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

我有一个包含文本和数字以及空值的列表。我想拍:

products = [[], [], [], [], [], [], [], [], [], [], ['productid="6836518"', 'productid="5965878"', 'productid="3851171"'], ['productid="6455623"'], [], ['productid="8024914"', 'productid="2871360"', 'productid="6694729"', 'productid="6760262"'], [], [], ['productid="6466698"', 'productid="5340641"', 'productid="6071996"', 'productid="5379225"'], ['productid="6683916"', 'productid="6690577"', 'productid="7117851"'], ['productid="7094467"'], ['productid="6628351"'], ['productid="5897930"'], ['productid="6812437"', 'productid="5379225"'], ['productid="7918467"', 'productid="7918466"'], []]

并返回如下内容:

products2 =  [6836518, 5965878, 3851171, 6455623, 8024914, 2871360, 6694729, 6760262, 6466698, 5340641, 6071996, 5379225, 6683916, 6690577, 7117851, 7094467, 6628351, 5897930, 6812437, 5379225, 7918467, 7918466] 

Tags: 文本内容列表数字products空值productidproducts2
3条回答
import re

data = [[], [], [], [], [], [], [], [], [], [], ['productid="6836518"', 'productid="5965878"', 'productid="3851171"'], ['productid="6455623"'], [], ['productid="8024914"', 'productid="2871360"', 'productid="6694729"', 'productid="6760262"'], [], [], ['productid="6466698"', 'productid="5340641"', 'productid="6071996"', 'productid="5379225"'], ['productid="6683916"', 'productid="6690577"', 'productid="7117851"'], ['productid="7094467"'], ['productid="6628351"'], ['productid="5897930"'], ['productid="6812437"', 'productid="5379225"'], ['productid="7918467"', 'productid="7918466"'], []]
clean = []

for l in data:
    for item in l:
        clean.append(int(re.search('\d+', item).group(0)))

print(clean)

此单行解决方案应使用re

import re
product = [int(re.search("\d+",e).group()) for l in products for e in l]

product的结果:

[6836518,
 5965878,
 3851171,
 6455623,
 8024914,
 2871360,
 6694729,
 6760262,
 6466698,
 5340641,
 6071996,
 5379225,
 6683916,
 6690577,
 7117851,
 7094467,
 6628351,
 5897930,
 6812437,
 5379225,
 7918467,
 7918466]

所以请检查您的数据结构。您有一个列表列表,其中那些内部列表包含零或看起来像'productid="0123456"'的元素,您希望将这些数字取出。你知道吗

您应该能够使用itertools.chain来实现:

products2 = []

for el in itertools.chain.from_iterable(products):
    if 'productid' in el:
        _, num = el.split('=')
        num = int(num.strip('"'))
        products2.append(num)

如果您可能有productid='12345'..."12345",您可以用num = int(num.strip('"\''))来去除这两种类型的引号(注意转义的单引号,我认为它看起来比等价的""""'"""更干净)

相关问题 更多 >

    热门问题