如何将此列表理解转换为 for 循环,但我不能 [重复]
Posted
技术标签:
【中文标题】如何将此列表理解转换为 for 循环,但我不能 [重复]【英文标题】:How can I convert This List comprehension to for loop but I can't [duplicate] 【发布时间】:2021-11-13 16:00:22 【问题描述】:def keys(dic):
return [key for key in dic]
print(keys(dic))
我想将列表理解替换为 for 循环
【问题讨论】:
【参考方案1】:def f(dic):
new_keys = []
for i in dic:
new_keys.append(i)
return new_keys
def g(dic):
return list(dic)
def h(dic):
return [*dic]
dic = 'a': 1, 'b': 2
print(f(dic))
print(g(dic))
print(h(dic))
f 做你想做的事,但我不会使用 f。我会选择g,也许看看h。 h 适用于 python >= 3.5。点击此处了解更多详情:How to return dictionary keys as a list in Python?
检查输出
['a', 'b']
['a', 'b']
['a', 'b']
【讨论】:
谢谢你真的帮助我 helloffffffffff def items(dic): # li = [] # for item in dic: # it = (item, dic[item]) # li.append(it) # return li def items(dic): # li = [] # for item in dic: # it = (item, dic[item]) # li.append(it) # return li def items(dic): # li = [] # for item in dic: # it = (item, dic[item]) # li.append(it) # return li【参考方案2】:这是您需要的吗?
def keys(dic):
key_list = []
for key in dic.keys():
list.append(key)
print(key)
return key_list
【讨论】:
谢谢你真的帮助我 def items(dic): # li = [] # for item in dic: # it = (item, dic[item]) # li.append(it) # return li以上是关于如何将此列表理解转换为 for 循环,但我不能 [重复]的主要内容,如果未能解决你的问题,请参考以下文章