使用python删除此列表中的none值

2024-09-27 00:13:37 发布

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

我想删除此列表中的“无”值

input= [(None, 'Ibrahimpatnam', 9440627084, None, 'Under Investigation'),
        (None, 'Ibrahimpatnam', 9440627084, None, 'Under Investigation')]

然后得到一个输出

^{pr2}$

Tags: none列表inputunderpr2investigationibrahimpatnam
3条回答

如果您想剥离,然后连接--list comprehension在这里工作得非常干净,而且不丢失可读性:

import itertools
stripped_lists = [ [x for x in sublist if x] for sublist in input_ ]

print(list(itertools.chain.from_iterable(stripped_lists )))

输出:

^{pr2}$

或者,如果您连接然后剥离,这是很好的和简短的:

print(list(x for x in itertools.chain.from_iterable(aa) if x))

试试这个:

input_= [(None, 'Ibrahimpatnam', 9440627084, None, 'Under Investigation'),
        (None, 'Ibrahimpatnam', 9440627084, None, 'Under Investigation')]
output = []
for each in input_:
    newList = list(filter(None,each))
    output = output+newList
print(output)

注意:不要使用input作为变量,它是python中的保留关键字。如果你只是用它来写这篇文章就没关系了。

您需要遍历列表(包含元组),然后遍历每个元组。检查每个元组的每个元素是否为None

a = [
    (None, "Ibrahimpatnam", 9_440_627_084, None, "Under Investigation"),
    (None, "Ibrahimpatnam", 9_440_627_084, None, "Under Investigation"),
]
b = [element for sub_tuple in a for element in sub_tuple if element is not None]
print(b)

你得到了

['Ibrahimpatnam', 9440627084, 'Under Investigation', 'Ibrahimpatnam', 9440627084, 'Under Investigation']

相关问题 更多 >

    热门问题