如何在每个字符相同时从列表中删除元素(Python)?

时间:2016-10-16 16:16:01

标签: python for-loop

sample = ['AAAA','ABCB','CCCC','DDEF']

我需要消除元素中每个字符与其自身相同的所有元素,例如。 AAAAA,CCCCC

output = ['ABCB','DDEF']

sample1 =[]
for i in sample:
    for j in i:
       if j == j+1:    #This needs to be corrected to if all elements in i identical to each other i.e. if all "j's" are the same
        sample1.pop(i)

打印样本

2 个答案:

答案 0 :(得分:6)

 sample = ['AAAA','ABCB','CCCC','DDEF']
 output = [sublist for sublist in sample if len(set(sublist)) > 1]

编辑回答评论。

sample = [['CGG', 'ATT'], ['ATT', 'CCC']]
output = []
for sublist in sample:
    if all([len(set(each)) > 1 for each in sublist]):
        output.append(sublist)

# List comprehension (doing the same job as the code above)
output2 = [sublist for sublist in sample if 
           all((len(set(each)) > 1 for each in sublist))]

答案 1 :(得分:2)

sample = ['AAAA','ABCB','CCCC','DDEF']

sample1 = []
for i in sample:
    if len(set(i)) > 1:
        sample1.append(i)