如何将计数器列表转换为项目和值组合在 python 中的列表?

How to convert a list of counters into a list with items and values combined in python?

我有

x = [('a', 1), ('ab', 1), ('abc', 1), ('abcd', 1), ('b', 1), ('bc', 1), ('bcd', 1), ('c', 1), ('cd', 1), ('d', 1)]

我想转换 x 中的每个元素,使得:

('a',1) --> 'a1';

('ab', 1) --> 'ab1';

('abc', 1) --> 'abc1';

供您参考:

这就是我得到 x 的方式:x = list(Counter(words).items())

假设您使用的是 Python 3.6+,您可以使用列表理解和 f 字符串:

x = [('a', 1), ('ab', 1), ('abc', 1), ('abcd', 1), ('b', 1), ('bc', 1), ('bcd', 1), ('c', 1), ('cd', 1), ('d', 1)]
output = [f'{first}{second}' for first, second in x]

如果您使用的是以前的版本:

output = ['{first}{second}'.format(first=first, second=second) for first, second in x]

试一试。

x = [('a', 1), ('ab', 1), ('abc', 1), ('abcd', 1), ('b', 1), ('bc', 1), ('bcd', 1), ('c', 1), ('cd', 1), ('d', 1)]
comb = [tup[0]+str(tup[1]) for tup in x]