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

2024-09-29 00:12:21 发布

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

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)

打印样本


Tags: tosamplein元素forifall字符
2条回答
sample = ['AAAA','ABCB','CCCC','DDEF']

sample1 = []
for i in sample:
    if len(set(i)) > 1:
        sample1.append(i)
 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))]

相关问题 更多 >