Kro*_*ter 10 python list unique distinct-values python-3.x
所以我有以下列表:
test_list = ['Hallo', 42, [1, 2], 42, 3 + 2j, 'Hallo', 'Hello', [1, 2], [2, 3], 3 + 2j, 42]
Run Code Online (Sandbox Code Playgroud)
现在我想从列表中获取唯一值并将其打印在屏幕上。我尝试过使用 set 函数,但这不起作用(Type error: unhasable type: 'list'),因为列表中存在 [1,2] 和 [2,3] 值。我尝试使用追加和扩展功能,但尚未找到解决方案。
期望:['你好', 42, [1,2], (3+2j), '你好', [2,3]]
def unique_list(a_list):
a = set(a_list)
print(a)
a_list = ['Hallo', 42, [1, 2], 42, 3 + 2j, 'Hallo', 'Hello', [1, 2], [2, 3], 3 + 2j, 42]
print(unique_list(a_list))
Run Code Online (Sandbox Code Playgroud)
如果列表包含不可散列的元素,请使用repr可与集合一起使用的可散列键创建:
def unique_list(a_list):
seen = set()
for x in a_list:
key = repr(x)
if key not in seen:
seen.add(key)
print(x)
Run Code Online (Sandbox Code Playgroud)
您可以在运行时间为 O(n^2) 的常规for循环中执行此操作。
def unique_list(a_list):
orig = a_list[:] # shallow-copy original list to avoid modifying it
uniq = [] # start with an empty list as our result
while(len(orig) > 0): # iterate through the original list
uniq.append(orig[0]) # for each element, append it to the unique elements list
while(uniq[-1] in orig): # then, remove all occurrences of that element in the original list
orig.remove(uniq[-1])
return uniq # finally, return the list of unique elements in order of first occurrence in the original list
Run Code Online (Sandbox Code Playgroud)
可能还有一种方法可以将其变成列表理解,这会更优雅,但我目前无法弄清楚。如果每个元素都是可散列的,您可以使用该set方法,这会更容易。
| 归档时间: |
|
| 查看次数: |
3837 次 |
| 最近记录: |