【发布时间】:2021-12-04 21:01:58
【问题描述】:
如果输入数据是列表,则正常工作
list_data = [7,10,9,20,2,5,15,6,25,2,8,17,23,9,24,45,3,22,6,20,4]
pos_1 = 0
pos_2 = 0
for i in range(len(list_data)):
if list_data[i] >= 25:
pos_1 = i
break
print(f"Position1 which has value greater than equal to 25: {pos_1}")
for i in range(pos_1+1,len(list_data)):
if list_data[i] >= 25:
pos_2 = i
break
print(f"Position2 which has value greater than equal to 25: {pos_2}")
输出(第二个for循环不会重复第一个for循环)
Position1 which has value greater than equal to 25: 8
Position2 which has value greater than equal to 25: 15
但如果数据是这样的字典
dic_data = {1: 10, 3: 20, 6: 15, 8: 25, 11: 17, 12: 23, 14: 24, 15: 45, 17: 22, 19: 20}
index_1 = 0
for i in range(len(dic_data)):
if(dic_data.values() >= 25):
pos_1 = dic_data.keys()
index_1 = i
break
print(f"Position1 which has value greater than equal to 25: {pos_1}")
for i in range(index_1+1,len(dic_data)):
if(dic_data.values() >= 25):
pos_2 = dic_data.keys()
break
print(f"Position2 which has value greater than equal to 25: {pos_2}")
当然一定是错误
如何处理字典数据?(这两个都不是我的实际代码,只是一个例子)
【问题讨论】:
-
使用字典,关于您的第一个代码,什么代表键和值?如果值高于 25 保留密钥?
-
“当然一定是错误”是什么意思?你还没有告诉我们第二个代码块的结果是什么。我建议您打印出字典的不同条件和功能,以便您可以看到它们的作用。因为我不认为这段代码在做你想做的事。
-
对我不清楚的问题向大家道歉。
标签: python list dictionary for-loop