博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
从python中的列表中获取唯一值[重复]
阅读量:2290 次
发布时间:2019-05-09

本文共 3409 字,大约阅读时间需要 11 分钟。

本文翻译自:

This question already has an answer here: 这个问题在这里已有答案:

  • 45 answers 45答案

I want to get the unique values from the following list: 我想从以下列表中获取唯一值:

[u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']

The output which I require is: 我需要的输出是:

[u'nowplaying', u'PBS', u'job', u'debate', u'thenandnow']

This code works: 此代码有效:

output = []for x in trends:    if x not in output:        output.append(x)print output

is there a better solution I should use? 我应该使用更好的解决方案吗?


#1楼

参考:


#2楼

what type is your output variable? 你的输出变量是什么类型的?

Python are what you just need. Python 是您所需要的。 Declare output like this: 声明输出如下:

output = set([]) # initialize an empty set

and you're ready to go adding elements with output.add(elem) and be sure they're unique. 你准备output.add(elem)添加元素,并确保它们是唯一的。

Warning: sets DO NOT preserve the original order of the list. 警告:设置不保留列表的原始顺序。


#3楼

First declare your list properly, separated by commas. 首先正确声明您的列表,用逗号分隔。 You can get the unique values by converting the list to a set. 您可以通过将列表转换为集合来获取唯一值。

mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']myset = set(mylist)print(myset)

If you use it further as a list, you should convert it back to list by doing: 如果您进一步将其用作列表,则应通过执行以下操作将其转换回列表:

mynewlist = list(myset)

Another possibility, probably faster would be to use a set from the beginning, instead of a list. 另一种可能性,可能更快,就是从头开始使用一个集合,而不是列表。 Then your code should be: 那你的代码应该是:

output = set()for x in trends:    output.add(x)print(output)

As it has been pointed out, the sets do not maintain the original order. 正如已经指出的那样,集合不保持原始顺序。 If you need so, you should look up about the . 如果您需要,您应该查看 。


#4楼

The example you provided does not correspond to lists in Python. 您提供的示例与Python中的列表不对应。 It resembles a nested dict, which is probably not what you intended. 它类似于嵌套的字典,可能不是你想要的。

A Python list: Python列表:

a = ['a', 'b', 'c', 'd', 'b']

To get unique items, just transform it into a set (which you can transform back again into a list if required): 要获取唯一项目,只需将其转换为一个集合(如果需要,您可以将其转换回列表):

b = set(a)print b>>> set(['a', 'b', 'c', 'd'])

#5楼

First thing, the example you gave is not a valid list. 首先,您提供的示例不是有效列表。

example_list = [u'nowplaying',u'PBS', u'PBS', u'nowplaying', u'job', u'debate',u'thenandnow']

Suppose if above is the example list. 假设上面是示例列表。 Then you can use the following recipe as give the itertools example doc that can return the unique values and preserving the order as you seem to require. 然后,您可以使用以下配方作为itertools示例文档,该文档可以返回唯一值并保留您看起来需要的顺序。 The iterable here is the example_list 这里的iterable是example_list

from itertools import ifilterfalsedef unique_everseen(iterable, key=None):    "List unique elements, preserving order. Remember all elements ever seen."    # unique_everseen('AAAABBBCCDAABBB') --> A B C D    # unique_everseen('ABBCcAD', str.lower) --> A B C D    seen = set()    seen_add = seen.add    if key is None:        for element in ifilterfalse(seen.__contains__, iterable):            seen_add(element)            yield element    else:        for element in iterable:            k = key(element)            if k not in seen:                seen_add(k)                yield element

#6楼

  1. At the begin of your code just declare your output list as empty: output=[] 在代码的开头只是将输出列表声明为空: output=[]
  2. Instead of your code you may use this code trends=list(set(trends)) 您可以使用此代码来代替您的代码trends=list(set(trends))

转载地址:http://sjcnb.baihongyu.com/

你可能感兴趣的文章
poj3259——Wormholes(Eellman-Ford算法)
查看>>
poj1502——MPI Maelstrom(dijkstra算法)
查看>>
poj1287——Networking(prim)
查看>>
poj2031——Building a Space Station(prim)
查看>>
poj2412——Constructing Roads(最小生成树变形)
查看>>
poj1789——Truck History(最小生成树+prim)
查看>>
poj2349——Arctic Network(最小生成树+prim)
查看>>
poj1751——Highways(部分确定的最小生成树)
查看>>
hdu1875——畅通工程再续(最小生成树)
查看>>
Lightoj1189——Sum of Factorials(阶乘的和+贪心)
查看>>
Lightoj1202——Bishops(找规律)
查看>>
Lightoj1211——Intersection of Cubes(立方体的交)
查看>>
Lightoj1212——Double Ended Queue(STL)
查看>>
Lightoj1216——Juice in the Glass (计算几何)
查看>>
Lightoj1241——Pinocchio (模拟+ceil)
查看>>
Lightoj1249——Chocolate Thief (模拟)
查看>>
Lightoj1082——Array Queries(线段树+求区间最小值)
查看>>
Lightoj1140——How Many Zeroes?(数位dp)
查看>>
Lightoj1068——Investigation(数位dp)
查看>>
Lightoj1205——Palindromic Numbers(数位dp+回文数)
查看>>