有没有更好的方法在Python中实现这个功能?或者说,这种方法是否可行?
x = ('a', 'b', 'c')
y = ('d', 'e', 'f')
z = ('g', 'e', 'i')
l = [x, y, z]
s = set([e for (_, e, _) in l])
我看起来有点丑,但不需要编写复杂的“get_unique_elements_from_tuple_list”函数就能实现所需功能... ;)
编辑:s的期望值为set(['b','e'])
有没有更好的方法在Python中实现这个功能?或者说,这种方法是否可行?
x = ('a', 'b', 'c')
y = ('d', 'e', 'f')
z = ('g', 'e', 'i')
l = [x, y, z]
s = set([e for (_, e, _) in l])
我看起来有点丑,但不需要编写复杂的“get_unique_elements_from_tuple_list”函数就能实现所需功能... ;)
编辑:s的期望值为set(['b','e'])
没问题,这就是集合的作用。我会改变其中一件事:
s = set(e[1] for e in l)
这样做可以提高可读性。请注意,我还将列表推导式转换为生成器表达式,无需创建临时列表。