Vis*_*hal 2 python set python-3.x
In general, converting a list to set is simple, as below:
a = [1,2,3,1]
set_a = set(a) # set([1, 2, 3])
Run Code Online (Sandbox Code Playgroud)
Now, I want to convert a list of tuples to set, only considering the first value of tuple.
a = [(1,"a1"), (2,"b2"), (3, "c3"), (1, "d4")]
set_a = some_magic(a)
# 1) set_a = set([(1,"a1"), (2,"b2"), (3, "c3")]) or
# 2) set_a = set([(1, "d4"), (2,"b2"), (3, "c3")])
# Both (1) or (2) are acceptible outputs.
Run Code Online (Sandbox Code Playgroud)
Is there a "one-line" trick I could use instead of some_magic function mentioned above?
I want to avoid making a separate list for book-keeping which of the first index of tuples are already used [which would have been the obvious answer otherwise]
try this:
set(dict(a).items())
Run Code Online (Sandbox Code Playgroud)
dict(a) will turn the list into a dictionary where the keys get overwritten by each occurrence
the .items() extracts each key-value pair into a dict_items list of tuples
the set() turns it into the set you want
Note: this will give you the second example, keeping the very last unique tuple key. If you want the first one, a different approach will be needed
| 归档时间: |
|
| 查看次数: |
104 次 |
| 最近记录: |