首页 > 解决方案 > 在不丢失括号的情况下,将列表转换为集合,然后与集合列表一起“加入”

问题描述

(例如。[(1,2,3),(4,5,6),(7,8,9)]

我正在使用 set 来确保没有重复的集合set(check_com_of_three)

>>>set(new_c[a]) + str(',') + set(check_com_of_three)

输出

Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    set(new_c[a]) + str(',') + set(check_com_of_three)
TypeError: unsupported operand type(s) for +: 'set' and 'str'

关于我为什么做错的任何解释,以及最好和最简单的方法是什么?

标签: pythonset

解决方案


由于您已经有一个列表,您可以使用insert索引位置:

x = (1,2,3)
y = [(4,5,6), (7,8,9)]

y.insert(0, tuple(x))
print(y)

输出

[(1,2,3), (4,5,6), (7,8,9)]

推荐阅读