如何从Python元组列表中删除所有字符串

6

我正在尝试从一个元组列表中删除所有字符串

ListTuples = [(100, 'AAA'), (80, 'BBB'), (20, 'CCC'), (40, 'DDD'), (40, 'EEE')]

我已经开始尝试寻找解决方案:

output = [i for i in ListTuples if i[0] == str]

print(output)

但是我似乎无法理解如何获得这样的输出:
[(100), (80), (20), (40), (40)]

格式始终为 (int, str)。

1
你知道你总是会有形式为[(<int>, <str>), ...]的项目吗? - Jack Moody
2
如果格式总是(int,str),则以下可能是一个简单的解决方案: output = [(i[0],) for i in ListTuples] - Mark
@MarkNijboer 是的,这也很完美。 - a.rowland
5个回答

9

使用嵌套元组推导和isinstance

output = [tuple(j for j in i if not isinstance(j, str)) for i in ListTuples]

输出:

[(100,), (80,), (20,), (40,), (40,)]

请注意元组中的尾随逗号,以将它们与例如(100)区分开来,后者与100相同。

@RoadRunner,不是这样的,[(100), (80), (20), (40), (40)] 是有效的 Python 代码,它是一个整数列表! - jpp
谢谢,这个完美地解决了我的问题!我只需要将isinstance(j, str)更改为isinstance(j, int),就可以得到我想要的整数值。我会接受这个答案。 - a.rowland
1
我认为这与楼主期望的输出是匹配的,或者更准确地说,这是楼主(很可能)打算展示的内容,而不是Python对此的解释。 - tobias_k
@jpp 这是真的,但如果没有括号,它就不会被打印出来。 - meowgoesthedog
1
如果您想要“删除所有字符串”,那么您应该使用not isinstance(j, str),否则它将是“保留所有整数”,这并不严格相同。(尽管在您的示例中两者是等价的。) - tobias_k
显示剩余2条评论

2

由于提取每个元组的第一个项目就足够了,因此您可以解包并使用列表推导式。对于一个元组列表:

res = [(value,) for value, _ in ListTuples]  # [(100,), (80,), (20,), (40,), (40,)]

如果您只需要一个整数列表:

res = [value for value, _ in ListTuples]     # [100, 80, 20, 40, 40]

如果想要一个功能性的替代方案,可以使用operator.itemgetter

from operator import itemgetter
res = list(map(itemgetter(0), ListTuples))   # [100, 80, 20, 40, 40]

1
这是另一种使用 filter() 的解决方案:
def non_string(x):
    return not isinstance(x, str)

print([tuple(filter(non_string, x)) for x in ListTuples])
# [(100,), (80,), (20,), (40,), (40,)]

0

试试这个

ListTuples = [(100, 'AAA'), (80, 'BBB'), (20, 'CCC'), (40, 'DDD'), (40, 'EEE')]

ListInt = []
ListStr = []

for item in ListTuples:
    strAux = ''
    intAux = ''
    for i in range(0, len(item)):

        if(isinstance(item[i], str)):
            strAux+=item[i] 
        else:
            intAux+=str(item[i])


    ListStr.append(strAux)
    ListInt.append(intAux)


print(ListStr)

'''TO CONVERT THE STR LIST TO AN INT LIST'''
output= list(map(int, ListInt)) 
print(output)

输出结果为[100, 80, 20, 40, 40]


那些“aux”累加器是用来干什么的?为什么不直接在if/else中使用appen?这将无法处理[(1,“foo”,3)]或任何其他具有多个相同类型的元组,对于任何其他情况,这些“aux”变量也没有用处。 - tobias_k
如果在if/else中使用'append',它将在for循环中返回'A','A','A','B','B'等等。如果尝试[(1,“foo”,3)],它将返回13和foo。 - Henrique Zanferrari
不,它不会,因为您没有在字符串中迭代字符,只是在元组中迭代元素。而且,是的,它将返回那个值,我认为这不是 OP 所期望的。 - tobias_k

0
我们使用 type(value) 来检查一个特定的值是否为字符串。
output = [tuple([j for j in i if type(j)!=str]) for i in ListTuples]
print(output)
    [(100,), (80,), (20,), (40,), (40,)]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接