九御寒 发表于 2022-3-15 19:06:45

列表和元组的转换

lst = [("triangle", "shape"), ("red", "color"), ("square", "shape"), ("yellow", "color"), ("green", "color"),
       ("circle", "shape")]
lst_new = [, x] for x in lst]
# print(lst_new)
lst_sort = sorted(lst_new)
print(f"按照标签排序后的列表:{lst_sort}")
lst_colors = for x in lst_sort if x == "color"]
print(f"颜色列表:{lst_colors}")


结果:
按照标签排序后的列表:[['color', 'green'], ['color', 'red'], ['color', 'yellow'], ['shape', 'circle'], ['shape', 'square'], ['shape', 'triangle']]
颜色列表:['green', 'red', 'yellow']

怎么样才可以让['color', 'green']的[]变成()

ckblt 发表于 2022-3-15 19:12:02

lst_colors = tuple(lst_colors)

isdkz 发表于 2022-3-15 19:14:31

lst = [("triangle", "shape"), ("red", "color"), ("square", "shape"), ("yellow", "color"), ("green", "color"),
       ("circle", "shape")]
lst_new = [(x, x) for x in lst]
# print(lst_new)
lst_sort = sorted(lst_new)
print(f"按照标签排序后的列表:{lst_sort}")
lst_colors = for x in lst_sort if x == "color"]
print(f"颜色列表:{lst_colors}")

isdkz 发表于 2022-3-15 19:15:26

lst_new = [(x, x) for x in lst]       # 这个由中括号改成小括号
页: [1]
查看完整版本: 列表和元组的转换