Python中字符串的元组列表

时间:2022-11-24 19:36:23

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?

但是有更简单的方法吗?可能是一行吗?

3 个解决方案

#1


11  

You can concatenate each pair of letters, then join the whole result in a generator expression

您可以连接每对字母,然后将整个结果连接到生成器表达式中

>>> ''.join(i+j for i,j in zip(l[1::2], l[::2]))
'7bea6a7ac9b796d957427cb8f37f9b44'

#2


2  

You can just use a simple list comprehension to swap (provide you are sure to have an even size) and then join:

你可以使用一个简单的列表理解来交换(提供你肯定有一个偶数大小),然后加入:

''.join([ l[i+1] + l[i] for i in range(0, len(l), 2) ])

#3


1  

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)) )

#1


11  

You can concatenate each pair of letters, then join the whole result in a generator expression

您可以连接每对字母,然后将整个结果连接到生成器表达式中

>>> ''.join(i+j for i,j in zip(l[1::2], l[::2]))
'7bea6a7ac9b796d957427cb8f37f9b44'

#2


2  

You can just use a simple list comprehension to swap (provide you are sure to have an even size) and then join:

你可以使用一个简单的列表理解来交换(提供你肯定有一个偶数大小),然后加入:

''.join([ l[i+1] + l[i] for i in range(0, len(l), 2) ])

#3


1  

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)) )