简体   繁体   English

Python将元组列表的第二部分合并到字符串列表中

[英]Python merge second part of tuple list into list of strings

I have only recently started learning Python, and I have looked at similar questions and cannot seem to find an example that helps - I have this list of tuples currently: 我刚刚开始学习Python,我看过类似的问题,似乎找不到一个有用的例子 - 我目前有这个元组列表:

 [('E', ['E', 'F', 'C', 'C']), ('F', ['A', 'D', 'D', 'B']), ('I', ['F', 'D', 'F', 'D']), ('R', ['E', 'B', 'D', 'B']), ('S', ['B', 'C', 'C', 'D'])]

and I want to split them up into a list of strings, so that they look like this: 我想把它们分成一个字符串列表,这样它们看起来像这样:

['EFCC', 'ADDB', 'FDFD', 'EBDB', 'BCCD']

I have tried to use the '.join' function for this, as shown below: 我试图使用'.join'函数,如下所示:

stringList = "".join([str(x[1]) for x in sortedList])

but this provides me with a list in the form: 但这为我提供了一个表格列表:

['B', 'D', 'E', 'C']['B', 'C', 'B', 'D']['E', 'C', 'D', 'C']['B', 'C', 'D', 'C']['C', 'E', 'F', 'A']

I think I am using the join method wrong, but after changing a few bits about in it, I can't figure out how to get the format I want. 我认为我使用的是连接方法错误,但在更改了一些内容之后,我无法弄清楚如何获得我想要的格式。

Your problem is str(x[1]) . 你的问题是str(x[1])

x[1] is a list, and you convert it to a string: x[1]是一个列表,您将其转换为字符串:

>>> x = ('E', ['E', 'F', 'C', 'C'])
>>> x[1]
['E', 'F', 'C', 'C']

>>> str(x[1])
"['E', 'F', 'C', 'C']"

What you want is to join the elements of the list: 你想要的是加入列表的元素:

>>> ''.join(x[1])
'EFCC'

So your code would become: 所以你的代码将成为:

[''.join(x[1]) for x in sortedList]

Use a list comprehension and join the strings, like so. 使用列表推导并加入字符串,就像这样。

t = [('E', ['E', 'F', 'C', 'C']), ('F', ['A', 'D', 'D', 'B']), ('I', ['F', 'D', 'F', 'D']), ('R', ['E', 'B', 'D', 'B']), ('S', ['B', 'C', 'C', 'D'])]

x = [''.join(b) for a, b in t]
print(x)

You can use map: 你可以使用map:

print map(lambda x: "".join(x[1]),t)

Output: 输出:

['EFCC', 'ADDB', 'FDFD', 'EBDB', 'BCCD']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM