在python列表中查找元组中的唯一元素

时间:2022-09-28 14:25:09

Is there a better way to do this in python, or rather: Is this a good way to do it?

有没有更好的方法在python中执行此操作,或者更确切地说:这是一个很好的方法吗?

x = ('a', 'b', 'c')
y = ('d', 'e', 'f')
z = ('g', 'e', 'i')

l = [x, y, z]

s = set([e for (_, e, _) in l])

I looks somewhat ugly but does what i need without writing a complex "get_unique_elements_from_tuple_list" function... ;)

我看起来有些难看,但在没有编写复杂的“get_unique_elements_from_tuple_list”函数的情况下完成了我的需要...;)

edit: expected value of s is set(['b','e'])

编辑:设置s的期望值(['b','e'])

1 个解决方案

#1


22  

That's fine, that's what sets are for. One thing I would change is this:

那没关系,这就是套装的用途。我要改变的一件事是:

s = set(e[1] for e in l)

as it enhances readability. Note that I also turned the list comprehension into a generator expression; no need to create a temporary list.

因为它增强了可读性。请注意,我还将列表推导转换为生成器表达式;无需创建临时列表。

#1


22  

That's fine, that's what sets are for. One thing I would change is this:

那没关系,这就是套装的用途。我要改变的一件事是:

s = set(e[1] for e in l)

as it enhances readability. Note that I also turned the list comprehension into a generator expression; no need to create a temporary list.

因为它增强了可读性。请注意,我还将列表推导转换为生成器表达式;无需创建临时列表。