Python中列表的唯一值

2024-09-28 19:23:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有以下列表:

[
    u'aaaaa', 
    [1, 6, u'testing', 20.0, 18.0, 2.0, 'In time'], 
    u'zzzzzz', 
    [1, 6, u'testing', 20.0, 18.0, 2.0, 'In time'], 
    [1, 1, u'xyz ', 30.0, 25.0, 5.0, 'On Going'], 
    [2, 1, u'abcd', 10.0, 8.0, 2.0, 'In time'], 
    u'bbbbb', 
    [1, 6, u'testing', 20.0, 18.0, 2.0, 'In time'], 
    [1, 1, u'xyz ', 30.0, 25.0, 5.0, 'On Going'], 
    [2, 1, u'abcd', 10.0, 8.0, 2.0, 'In time'], 
    [1, 7, u'develop', 20.0, 15.0, 5.0, 'On Going']
]

我想要以下python输出:

^{pr2}$

请建议我如何在python中使用manageorder。在


Tags: in列表timeontesting建议abcdgoing
3条回答

下面将给出所需的输出。它使用字典来识别重复条目。在

entries = [
    u'aaaaa', [1, 6, u'testing', 20.0, 18.0, 2.0, 'In time'],
    u'zzzzzz', [1, 6, u'testing', 20.0, 18.0, 2.0, 'In time'], 
    [1, 1, u'xyz ', 30.0, 25.0, 5.0, 'On Going'], 
    [2, 1, u'abcd', 10.0, 8.0, 2.0, 'In time'],
    u'bbbbb', 
    [1, 6, u'testing', 20.0, 18.0, 2.0, 'In time'], 
    [1, 1, u'xyz ', 30.0, 25.0, 5.0, 'On Going'], 
    [2, 1, u'abcd', 10.0, 8.0, 2.0, 'In time'], 
    [1, 7, u'develop', 20.0, 15.0, 5.0, 'On Going']]

d = {}
output = []
entry = []

for item in entries:
    if type(item) == type([]):
        t = tuple(item)
        if t not in d:
            d[t] = 0
            entry.append(item)
    else:
        if len(entry):
            output.append(entry)

        entry = [item]

output.append(entry)

print output

这将产生以下输出:

^{pr2}$

使用Python2.7进行测试

更新:如果需要列表格式,只需在上面的脚本中将[]添加到item中,如下所示:

entry.append([item])

这将产生以下输出:

[[u'aaaaa', [[1, 6, u'testing', 20.0, 18.0, 2.0, 'In time']]], [u'zzzzzz', [[1, 1, u'xyz ', 30.0, 25.0, 5.0, 'On Going']], [[2, 1, u'abcd', 10.0, 8.0, 2.0, 'In time']]], [u'bbbbb', [[1, 7, u'develop', 20.0, 15.0, 5.0, 'On Going']]]]

如果要从列表中获取所有唯一值:

mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
mylist = [list(x) for x in set(tuple(x) for x in testdata)]
print myset # This is now a set containing all unique values.
# This will not maintain the order of the items

1)我真的认为你应该看看Python字典。你看他们的输出会更有意义。在

2)在这种情况下,如果我理解正确,您希望将包含字符串或列表元素的列表转换为列表列表。这个列表列表应该有一个起始元素作为字符串,其余元素作为主列表中的以下列表项,直到找到下一个字符串为止。(至少从你的例子来看是这样的)。在

output_list = []
for elem in main_list:
    if isinstance(elem,basestring):
        output_list.append([elem])
    else:
        output_list[-1].append(elem)

相关问题 更多 >