简体   繁体   English

除了循环之外还有其他方法可以从任何序列数据(Python)更新字典吗?

[英]Is there any alternative ways other than loop to update the dictionary from any sequence data (Python)?

I have a code to update a dictionary like this : 我有一个代码来更新这样的字典:

c = { }
for i in ID :
    d = {i : V[i]}
    c.update(d)

Both ID and V are sequence data with a complex and huge items, where ID is a list and V is a dictionary. ID和V都是具有复杂和巨大项目的序列数据,其中ID是列表,V是字典。

Is there any ways in python to do that logic without using loop processes like "for"? python中有没有办法在不使用像“for”这样的循环过程的情况下执行该逻辑?

The use of loop processes take a lot of iteration impacted on run time. 循环过程的使用会在运行时受到很多迭代的影响。

No, you can't avoid a loop but you can try these alternatives: 不,你不能避免循环,但你可以尝试这些替代方案:

c = { }
for i in ID :
    c[i] = V[i]

or 要么

c = dict([(i, V[i]) for i in ID])

or 要么

c = {i: V[i] for i in ID}

the short way of your code is: 你的代码的简短方法是:

c.update({i:V[i] for i in ID})

also you could use map , but it will iterate over 你也可以使用map ,但它会迭代

c.update(dict(map(lambda i:(i,V[i]),ID)))

Its all O(n) and you could just move it into C part rather than Python by using above notations! 它的所有O(n)你可以通过使用上面的符号将它移动到C部分而不是Python!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python字典检查是否存在除给定键以外的任何键 - python dictionary check if any key other than given keys exist 有没有其他方法可以在 Python 中完成此任务? - Is there any other ways to accomplish this task in Python? 还有其他方法可以对 python 中的 null 列表进行排序吗? - are there any other ways to sort null lists in python? 是否有其他方法可以检查python列表中特定索引的值是否为空 - Is there any alternative ways to check the value of particular index is empty or not in python list 除了身份验证之外,还有其他方法可以区分用户吗? - Are there any ways other than authentication to tell the users apart? 除了在 Google App Engine Flex 环境中部署 python flask 应用程序之外,还有其他替代方法吗? - Is there any alternative approach other than deploying python flask application in Google app engine flex environment? Python:确定顺序中的任何项是否与任何其他项相同 - Python: determining whether any item in sequence is equal to any other 有什么方法可以对字典中的所有列表值求和吗? - Are there any ways to sum all the list values that are from dictionary? 乘0比Python中的任何其他乘法快吗? - Is multiplying by 0 faster than any other multiplication in Python? python libtorrent有什么选择吗? - is there any alternative to python libtorrent?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM