[英]List of tuple to string in Python
I have a list like this: 我有一个这样的列表:
l = ['b', '7', 'a', 'e', 'a', '6', 'a', '7', '9', 'c', '7', 'b', '6', '9', '9', 'd', '7', '5', '2', '4', 'c', '7', '8', 'b', '3', 'f', 'f', '7', 'b', '9', '4', '4']
and I want to make a string from it like this: 我想像这样从它做一个字符串:
7bea6a7ac9b796d957427cb8f37f9b44
I did: 我做了:
l = (zip(l[1:], l)[::2])
s = []
for ll in l:
s += ll
print ''.join(s)
But is there any simpler way? 但有没有更简单的方法? May be, in one line? 可能是一行吗?
You can concatenate each pair of letters, then join
the whole result in a generator expression 您可以连接每对字母,然后将整个结果join
到生成器表达式中
>>> ''.join(i+j for i,j in zip(l[1::2], l[::2]))
'7bea6a7ac9b796d957427cb8f37f9b44'
你可以使用一个简单的列表理解来交换(提供你肯定有一个偶数大小)然后加入:
''.join([ l[i+1] + l[i] for i in range(0, len(l), 2) ])
Group adjacent list items using zip; 使用zip对相邻列表项进行分组;
group_adjacent = lambda a, k: zip(*([iter(a)] * k))
Then concatenate them by swapping in the for loop 然后通过交换for循环来连接它们
print (''.join( j+i for i,j in group_adjacent(l,2)) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.