创建Python列表和跳过元素

时间:2017-04-03 17:00:52

标签: list python-3.x

如何使用[x for x in input]创建列表列表(其中input是字符串列表)并在满足特定条件时跳过元素?例如,这是列表列表:

[['abc', 'def', 'ghi'], ['abc', 'd_f', '+hi'], ['_bc', 'def', 'ghi']]

这应该是输出 - 跳过的元素包含' _'或者' +':

[['abc', 'def', 'ghi'], ['abc'], ['def', 'ghi']]

谢谢!

3 个答案:

答案 0 :(得分:0)

您需要一个子列表理解:

result = []
for sub in input:
    result.append([])
    for item in sub:
        should_add = True
        for char in '_+':
            if char in item:
                should_add = False
                break
        if should_add:
            result[-1].append(item)

这是简化版:

print("This first text and " , end="")

print("second text will be on the same line")

print("Unlike this text which will be on a newline")

答案 1 :(得分:0)

非常类似于另一个答案,除了测试字符串是否只包含字母数字字符而不是特定'_''+'。循环遍历每个子列表,然后遍历每个子列表中的字符串。

filtered = [[s for s in l if s.isalpha()] for l in lists]

print(filtered)

[['abc', 'def', 'ghi'], ['abc'], ['def', 'ghi']]

答案 2 :(得分:0)

使用的另一个简短版本:

stuff= [['abc', 'def', 'ghi'], ['abc', 'd_f', '+hi'], ['_bc', 'def', 'ghi']]
unwanted = {'+', '-'}
filtered = [[item for item in s if not set(s) & unwanted] for s in stuff]