英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论