【问题标题】:How to make tuple with list of dictionary inpython?如何在python中使用字典列表制作元组?
【发布时间】:2021-12-07 19:45:51
【问题描述】:

我有一个字典列表,我想从标签值中创建元组,以便数组中的标签成对放置。 我该怎么做:

output: [
        {
          "title": "subject1",
          "tags": ['a','b'],
 },
        {
          "title": "subject2",
          "tags": ['c','d','f'],
 }]

我想要什么:

[(a,b),(c,d),(c,f),(d,f)]

【问题讨论】:

  • 你试过了吗?
  • @bichanna 是的,我写了一个代码,但它没有考虑重复的标签
  • @bichanna def get_edges_from_list(l): edges = [] for i,x in enumerate(l[:-1]): edges.append((x, l[i+1])) return edges label = set(sum([get_edges_from_list(x['tags']) for x in output], []))
  • @z-g 未来,请始终在问题中包含您的代码尝试????在 cmets 中很难阅读它们

标签: python dictionary tuples


【解决方案1】:

你可以使用itertools.combinations(... , 2)itertools.chain 得到你想要的,如下所示:

>>> import itertools

>>> results = [{"title": "subject1","tags": ['a','b'],},{"title": "subject2","tags": ['c','d','f'],}]

>>> lst = [list(itertools.combinations(res['tags'] , 2)) for res in results]
>>> lst
[[('a', 'b')], [('c', 'd'), ('c', 'f'), ('d', 'f')]]

>>> list(itertools.chain.from_iterable(lst))
[('a', 'b'), ('c', 'd'), ('c', 'f'), ('d', 'f')]

或者没有链条:

>>> import itertools
>>> results = [{"title": "subject1","tags": ['a','b'],},{"title": "subject2","tags": ['c','d','f'],}]
>>> out = []
>>> for res in results:
...    out += list(itertools.combinations(res['tags'] , 2))
>>> out
[('a', 'b'), ('c', 'd'), ('c', 'f'), ('d', 'f')]

# for more explanation
[1,2]+[3,4]
[1,2,3,4]

【讨论】:

  • 如何添加 itertools,pip install itertools 不起作用
  • @z-g 你有这个,这是原始的python库,你运行代码了吗?
【解决方案2】:

您可以使用itertools.combinations() 获取它。以下将起作用

from itertools import combinations

L1 = [{"title": "subject1", "tags": ['a','b']},
      {"title": "subject2", "tags": ['c','d','f']}]

res = []

for i in L1:
    tags = combinations(i["tags"], 2)
    res += list(tags)

print(res)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 2020-03-21
    • 1970-01-01
    相关资源
    最近更新 更多