移除Python中列表内元组的括号

huangapple go评论85阅读模式
英文:

Remove parentheses of tuples inside a list in python

问题

L = [(1, 2, 3), (3, 2, 1), (2, 1, 6), (7, 3, 2), (1, 0, 2)]

for x in L:
mm = ', '.join(str(j) for j in x)
L2.append(mm)
print(L2)

输出结果应该是:

L = ['1, 2, 3', '3, 2, 1', '2, 1, 6', '7, 3, 2', '1, 0, 2']

英文:

Given a list containing several tuples like this:
L = [(1, 2, 3), (3, 2, 1), (2, 1, 6), (7, 3, 2), (1, 0, 2)]

I want simply to remove the parentheses of tuples and join the numbers to create a list.

The output should be like this:

L = [1, 2, 3, 3, 2, 1, 2, 1, 6, 7, 3, 2, 1, 0, 2]

I tried the below code, it removed parentheses but add a single quotation ''.

for x in L:
    mm = (', '.join(str(j) for j in x))
    L2.append(mm)
print(L2)

Like this:
L = ['1, 2, 3', '3, 2, 1',' 2, 1, 6', '7, 3, 2', '1, 0, 2']

答案1

得分: 1

以下是翻译好的部分:

实际数据中没有括号或引号,只是在数据的表示中有。您的第一个列表包含5个元组,最终列表包含5个字符串,但您想要的列表包含15个整数。以下是实现您想要的简单方法:

L = [num for tup in L for num in tup]

这基本上与以下代码相同:

new_L = []
for tup in L:
    for num in tup:
        new_L.append(num)
英文:

There are actually no parentheses or quotation marks in the data, just in the representation of the data. Your first list contains 5 tuples, your final list contains 5 strings, but your desired list contains 15 integers. Here is a simple way to accomplish what you want:

L = [num for tup in L for num in tup]

Which is basically the same as:

new_L = []
for tup in L:
    for num in tup:
        new_L.append(num)

</details>



huangapple
  • 本文由 发表于 2023年7月18日 15:44:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76710535.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定