Python - 将列表列表转换为集合列表
给定一个包含列表的列表,任务是编写一个Python程序将其转换为包含集合的列表。
例子:
Input : [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]
Output : [{1, 2}, {1, 2, 3}, {2}, {0}]
Input : [[4, 4], [5, 5, 5], [1, 2, 3]]
Output : [{4}, {5}, {1, 2, 3}]
方法 1:使用列表理解
这可以使用列表理解轻松实现。我们只是遍历每个列表,将列表转换为集合。
Python3
# python3 program to convert list
# of lists to a list of sets
# initializing list
test_list = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]
# printing original list
print("The original list of lists : " + str(test_list))
# using list comprehension
# convert list of lists to list of sets
res = [set(ele) for ele in test_list]
# print result
print("The converted list of sets : " + str(res))
Python3
# Python3 code to demonstrate
# convert list of lists to list of sets
# using map() + set
# initializing list
test_list = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]
# printing original list
print("The original list of lists : " + str(test_list))
# using map() + set
res = list(map(set, test_list))
# print result
print("The converted list of sets : " + str(res))
输出:
he original list of lists : [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]
The converted list of sets : [{1, 2}, {1, 2, 3}, {2}, {0}]
方法 2:使用map() + set
我们可以使用 map函数和 set运算符的组合来执行此特定任务。 map函数绑定每个列表并将其转换为集合。
蟒蛇3
# Python3 code to demonstrate
# convert list of lists to list of sets
# using map() + set
# initializing list
test_list = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]
# printing original list
print("The original list of lists : " + str(test_list))
# using map() + set
res = list(map(set, test_list))
# print result
print("The converted list of sets : " + str(res))
输出:
The original list of lists : [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]
The converted list of sets : [{1, 2}, {1, 2, 3}, {2}, {0}]