【问题标题】:How to map a unique id (counting from 0) to items in sublists如何将唯一 id(从 0 开始计数)映射到子列表中的项目
【发布时间】:2014-08-02 20:53:38
【问题描述】:

假设我有

a = [['a1', 'b1'], ['a1', 'b2'], ['a2', 'b1'], ['a2', 'b4']]

结果我想要

a = [[0, 2], [0, 3], [1, 2], [1, 4]]

为每个子列表的第一项(即a[:][0])提供一个ID,然后继续每个子列表的第二项(即a[:][1]

我试过了:

>>> aa=[[] for cells in range(len(a))]
>>> for i in range(len(a)):
    for j in range(len(a[i])):
        aa[i].append(id(a[i][j]))

结果:

>>> aa
[[34378168, 51409056], [34378168, 51507304], [34301464, 51409056], [34301464, 51467576]]

这是“关闭”,但我希望 id 从 0 开始并继续。

我知道 id() 返回什么,我不需要。

【问题讨论】:

  • 不知道为什么这被否决了。 OP 有输入、预期输出、对所需内容的合理清晰描述以及解决它的尝试。
  • @MartijnPieters 我没有投反对票,但我仍然没有得到 OP 想要的东西。
  • @miindlek:他们想为每个字符串值生成一个唯一的数字。 a1 赋值为 0,a2 赋值为 1。这就是赋值的所有第一列值。然后继续计算唯一的第二列值:b1 得到 2,b2 得到 3,b4 得到 4。如果有更多唯一值,则分配更多数字。
  • @miindlek: 所以[['foo', 'bar'], ['spam', 'ham'], ['foo', 'baz'], ['spam', 'bar']] 会产生[[0, 2], [1, 3], [0, 4], [1, 2]]
  • 新来@MartijnPieters,你很有帮助。

标签: python list python-3.x uniqueidentifier


【解决方案1】:

使用collections.defaultdict()itertools.count();首先用zip() function 转置子列表,分配数字后再次转置:

from itertools import count
from collections import defaultdict

counts = defaultdict(lambda c=count(): next(c))

aa = zip(*((counts[cell] for cell in col) for col in zip(*a)))

每次未看到键时,defaultdict() 都会存储一个新的 count() 值,从而为每个字符串生成一个唯一的计数器。

演示:

>>> from itertools import count
>>> from collections import defaultdict
>>> a=[['a1', 'b1'], ['a1', 'b2'], ['a2', 'b1'], ['a2', 'b4']]
>>> counts = defaultdict(lambda c=count(): next(c))
>>> zip(*((counts[cell] for cell in col) for col in zip(*a)))
[(0, 2), (0, 3), (1, 2), (1, 4)]

【讨论】:

    猜你喜欢
    • 2021-09-21
    • 2020-05-21
    • 2018-05-14
    • 2010-09-16
    • 2021-11-23
    • 1970-01-01
    • 2011-06-06
    • 2016-06-22
    • 1970-01-01
    相关资源
    最近更新 更多