如何将计数器列表转换为在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]