我有以下问题:从字符串列表中,我必须从所有字符串中取出第一个字母,然后(从后到前),我必须取出第二个字母,在第三个字母之后从前到结束等等。
示例输入:
['abcd', 'efgh', 'ijkl', 'mnop']
输出应该是:
'aeimnjfbcgkoplhd'
到目前为止,我在这里,第一个“for”附加到数组:aeim 和 cgko 第二个“for”附加到数组:njfb 和 plhd。反正顺序不好,我需要aeim + njfb + cgko + plhd
array = []
if len(list_of_strings[0]) % 2 == 0: # if we have strings with even number of letters
for j in range(len(list_of_strings[0]/2)): # range(2) in our example
for i in range(len(list_of_strings)): # range(4) in our example
array.append(list_of_strings[i][j*2])
for j in range(1, len(list_of_strings[0]), 2): # range(1, 4, 2) in our example
for i in range(len(list_of_strings) - 1, -1, -1): # range(3, -1, -1) in our example
array.append(list_of_strings[i][j])
请帮忙。
谢谢
最佳答案
您可以使用 "unzip" (i.e. zip(*a)
) 来使用简单的单行代码和 str.join
:
a = ['abcd', 'efgh', 'ijkl', 'mnop']
b = ''.join(''.join(t[::1-2*(i%2)]) for i, t in enumerate(zip(*a)))
assert b == 'aeimnjfbcgkoplhd'
join
可以拿一个generator expression作为参数,在这种情况下,生成器表达式是
''.join(t[::1-2*(i%2)]) for i, t in enumerate(zip(*a))
表达式
zip(*a)
解压缩 a
中的字符串,即它返回一个生成器,该生成器生成包含每个字符串的所有第一个字母、所有第二个字母等的元组。
索引在
t[::1-2*(i%2)]
确保我们在每 2 次迭代中反转元组的顺序。
编辑
我将我的单线与 @cs95's answer 进行了基准测试,两者的性能在误差范围内是相同的。我认为在“真实代码”中我更喜欢他的解决方案,因为它更清晰。
关于python - 以之字形方式连接字符串列表的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61453420/