python:元组中具有相同第一个元素的组元素

2024-09-30 04:41:00 发布

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

我有一个这样的元组

[
(379146591, 'it', 55, 1, 1, 'NON ENTRARE', 'NonEntrate', 55, 1), 
(4746004, 'it', 28, 2, 2, 'NON ENTRARE', 'NonEntrate', 26, 2), 
(4746004, 'it', 28, 2, 2, 'TheBestTroll Group', 'TheBestTrollGroup', 2, 3)
]

我想换成这样:

^{pr2}$

所以对于任何元素,任何不是第一个元素的元素都在它的一个子元组中,如果下面的元素与第一个元素具有相同的元素,它将被设置为前一个元素的另一个子元组。在

所以我可以:

for i in data:
    # getting the first element of the list
    for sub_i in i[1]:
        # i access all the tuples inside

有什么功能可以做到这一点吗?在


Tags: thein元素fordatagroupit元组
3条回答

你可以使用collection.defaultdict公司名称:

data = [
    (379146591, 'it', 55, 1, 1, 'NON ENTRARE', 'NonEntrate', 55, 1), 
    (4746004, 'it', 28, 2, 2, 'NON ENTRARE', 'NonEntrate', 26, 2), 
    (4746004, 'it', 28, 2, 2, 'TheBestTroll Group', 'TheBestTrollGroup', 2, 3)
    ]
from collections import defaultdict
a = defaultdict(list)
a = defaultdict(list)


from collections import defaultdict
a = defaultdict(list)

for d in data:
    a[d[0]].append(d[1:])

for k,v in a.items():
    a[k] = tuple(a[k])

print(dict(a))

您可以使用Python3变量解包和OrderedDict来保持顺序:

from collections import OrderedDict
d = OrderedDict()
l = [
  (379146591, 'it', 55, 1, 1, 'NON ENTRARE', 'NonEntrate', 55, 1), 
  (4746004, 'it', 28, 2, 2, 'NON ENTRARE', 'NonEntrate', 26, 2), 
 (4746004, 'it', 28, 2, 2, 'TheBestTroll Group', 'TheBestTrollGroup', 2, 3)
]

for a, *b in l:
  if a in d:
     d[a].append(b)
  else:
     d[a] = [b]

final_data = [(a, tuple(map(tuple, b))) for a, b in d.items()]

输出:

^{2}$

使用defaultdict非常简单;您将默认值初始化为一个列表,然后将该项附加到同一个键的值:

lst = [
    (379146591, 'it', 55, 1, 1, 'NON ENTRARE', 'NonEntrate', 55, 1), 
    (4746004, 'it', 28, 2, 2, 'NON ENTRARE', 'NonEntrate', 26, 2), 
    (4746004, 'it', 28, 2, 2, 'TheBestTroll Group', 'TheBestTrollGroup', 2, 3)
]

from collections import defaultdict    ​
d = defaultdict(list)

for k, *v in lst:
    d[k].append(v)

list(d.items())
#[(4746004,
#  [('it', 28, 2, 2, 'NON ENTRARE', 'NonEntrate', 26, 2),
#   ('it', 28, 2, 2, 'TheBestTroll Group', 'TheBestTrollGroup', 2, 3)]),
# (379146591, [('it', 55, 1, 1, 'NON ENTRARE', 'NonEntrate', 55, 1)])]

如果顺序很重要,请使用可以记住插入顺序的OrderedDict

^{2}$

相关问题 更多 >

    热门问题