列表和元组的转换
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']的[]变成()
lst_colors = tuple(lst_colors) 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}") lst_new = [(x, x) for x in lst] # 这个由中括号改成小括号
页:
[1]