簡體   English   中英

來自兩個列表的字典

[英]Dictionary from two lists

我一直在尋找從兩個集合列表中創建字典。 如果我希望將每個列表中的每個項目都標記為鍵和值,例如,我知道如何執行此操作:

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

我想您正在尋找這樣的東西:

>>> 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

我們不知道更新列表二。 在我們這樣做之前,我們只能猜測。 習慣上講,無論得到什么值都應該是可迭代的(以便可以使用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配方中的 grouper ,其結果將與您的評論相同:

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}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM