我一直在寻找从两个集合列表中创建字典。如果我希望每个列表中的每个项目都标记为键和值,我理解如何执行此操作,例如:
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
答案 0 :(得分: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
答案 1 :(得分:0)
我们不知道更新清单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 recipes中的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}