Vis*_*hil 2 python string counter
我有
x = [('a', 1), ('ab', 1), ('abc', 1), ('abcd', 1), ('b', 1), ('bc', 1), ('bcd', 1), ('c', 1), ('cd', 1), ('d', 1)]
Run Code Online (Sandbox Code Playgroud)
我想转换 x 中的每个元素,以便:
('a',1) --> 'a1';
('ab', 1) --> 'ab1';
('abc', 1) --> 'abc1';
Run Code Online (Sandbox Code Playgroud)
供你参考:
这就是我得到 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]
Run Code Online (Sandbox Code Playgroud)
如果您使用的是以前的版本:
output = ['{first}{second}'.format(first=first, second=second) for first, second in x]
Run Code Online (Sandbox Code Playgroud)