【问题标题】:Dictionary from two lists来自两个列表的字典
【发布时间】:2014-04-01 17:03:17
【问题描述】:

我一直在寻找从两个集合列表创建字典。如果我希望每个列表中的每个项目都标记为键和值,我了解如何执行此操作,例如:

list_one = ['a', 'b', 'c']
list_two = ['1', '2', '3']
dictionary = dict(zip(list_one, list_two))
print dictionary
{'a': 1, 'b': 2, 'c': 3}

但是,我希望将 list_two 中的所有项目用作 list_one 中第一项的值。这将触发另一个循环,list_one 中的项目将发生变化,list_two 中的项目也会发生变化。

希望这是有道理的。

任何想法都将不胜感激。

用于创建列表的代码

def local_file(domain, user_list):
    cmd = subprocess.check_output(["tasklist", "/V", "/FO", "CSV"])
    tasks = csv.DictReader(cmd.splitlines(), dialect="excel")

    image_name = set()
    users = set()
    for task in tasks:
        if task['User Name'] == 'N/A': continue
        task_domain, task_user = task['User Name'].split('\\')
        if task_user in task['User Name']:
            image_name.add(task['Image Name'])
        else:
            pass
        if domain == task_domain and task_user in user_list:
            users.add(task['User Name'])
    sorted(image_name)
    print "Users found:\n"
    print '\n'.join(users)
    print "\nRuning the following services and applications.\n"
    print '\n'.join(image_name)
    if arguments['--app'] and arguments['--output'] == True:
        keys = users
        key_values = image_name
        dictionary = dict(zip(list_one, list_two))
        print dictionary
    elif arguments['--output'] == True:
        return users
    else:
        pass

【问题讨论】:

  • 您的结果字典会是什么样子?一个预期结果的例子将有助于澄清。
  • 预期输出是什么?
  • 预期结果{'c': ['8', '9', '10'], 'b': ['5', '6', '7'], 'a': ['1', '2', '3']}
  • 如果 list_two 是一个列表列表,您的原始代码就可以正常工作

标签: python dictionary


【解决方案1】:

我猜你正在寻找这样的东西:

>>> list_one = ['a', 'b', 'c']
>>> list_two = ['1', '2', '3']
>>> {item: list_two[:] for item in list_one}
{'c': ['1', '2', '3'], 'b': ['1', '2', '3'], 'a': ['1', '2', '3']}

对于 Python 2.6 及更早版本:

>>> dict((item, list_two[:]) for item in list_one)
{'c': ['1', '2', '3'], 'b': ['1', '2', '3'], 'a': ['1', '2', '3']}

请注意,[:] 是创建列表的浅表副本所必需的,否则所有值将指向同一个列表对象。

更新:

根据您的评论,list_two 将在迭代过程中发生变化,这里我使用迭代器在迭代过程中获取 list_two 的新值:

>>> out = {}
>>> it = iter([['1', '2', '3'], ['5', '6', '7'], ['8', '9', '10']])
>>> list_two = next(it)  #here `next` can be your own function.
>>> for k in list_one:
        out[k] = list_two
        list_two = next(it)  #update list_two with the new value.

 >>> out
{'c': ['8', '9', '10'], 'b': ['5', '6', '7'], 'a': ['1', '2', '3']}

#or

>>> it = iter([['1', '2', '3'], ['5', '6', '7'], ['8', '9', '10']])
>>> out = {}
>>> for k in list_one:
        list_two = next(it)  #fetch the value of `list_two`
        out[k] = list_two

【讨论】:

  • 也许吧,但我怀疑“再打一个循环,就会发生神奇的变化”条款。发电机可能会更好,因为它可以吸收环境变化。
  • 谢谢,这看起来可以工作,但是我需要编写函数来让它工作。可能会花一些时间 iNoob 的名字 iNoob 本质上是 iNoob ^_^
【解决方案2】:

我们不知道列表二的更新内容。在我们这样做之前,我们只能猜测。习惯上,任何获取值都应该是可迭代的(以便您可以使用next)。

res = {}
for k in list_one:
  res[k] = next(lists_two)

res = {k:next(lists_two) for k in list_one}

如果您有 Python 2.7 或更高版本。

对于与您的评论具有相同结果的示例,使用来自itertools recipesgrouper

from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

lists_two = grouper(range(3*len(list_one)), 3)
res = {k:next(lists_two) for k in list_one}

【讨论】:

  • 将我用来创建列表的功能代码添加到我的答案中
猜你喜欢
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 2019-03-26
  • 2011-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多