Python:使用“.join”处理数据(类型错误:序列项 0:预期字符串,找到元组)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28136435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:47:28  来源:igfitidea点击:

Python: Munging data with '.join' (TypeError: sequence item 0: expected string, tuple found)

pythonstringtuples

提问by jjjayn

I have data in following format:

我有以下格式的数据:

[('A', 'B', 'C'),
 ('B', 'C', 'A'),
 ('C', 'B', 'B')]

I'm looking to get this:

我想得到这个:

ABC
BCA
CBB

I'm able to convert one tuple at the time:

我可以一次转换一个元组:

>> "".join(data[0])
.. 'ABC'

However when I'm trying to conver the whole list Python gives me an error:

但是,当我尝试转换整个列表时,Python 给了我一个错误:

>> "".join(data[:])
.. TypeError: sequence item 0: expected string, tuple found

Any advice how I'll be able to convert the whole list?

有什么建议可以转换整个列表吗?

Thank you!

谢谢!

采纳答案by sapi

.joinexpects a sequence of strings, but you're giving it a sequence of tuples.

.join需要一个字符串序列,但你给它一个元组序列。

To get the result you posted, you'll need to join each element in each tuple, and then join each tuple together:

要获得您发布的结果,您需要将每个元组中的每个元素连接起来,然后将每个元组连接在一起:

print('\n'.join(''.join(elems) for elems in data))

This works because .joinwill accept a generator expression, allowing you to iterate over data(your list of tuples).

这是有效的,因为.join将接受生成器表达式,允许您迭代data(您的元组列表)。

We therefore have two joins going on: the inner join builds a string of the three letters (eg, 'ABC'), and the outer join places newline characters ('\n') between them.

因此,我们有两个连接进行:内连接构建一个由三个字母组成的字符串(例如,'ABC'),外连接'\n'在它们之间放置换行符()。

回答by Stavinsky

a = [('A', 'B', 'C'),  ('B', 'C', 'A'),  ('C', 'B', 'B')]
print ["".join(line) for line in a]

回答by GLHF

lst=[('A', 'B', 'C'),
 ('B', 'C', 'A'),
 ('C', 'B', 'B')]

for x in lst:
    print ("".join(x))

Output is;

输出是;

>>> 
ABC
BCA
CBB
>>> 

One-liner;

一字型;

print ("\n".join(["".join(x) for x in lst]))

You have to reach each element in the list first.

您必须首先到达列表中的每个元素。