[英]How to get element within range for nested list
Just started learning python, I have this assignment where I need do range within nested list.刚开始学习python,我有这个任务,我需要在嵌套列表中做范围。
tlist = [['Josh', 'Yes', 1, 4], ['Amy', 'No', 30, 4], ['Zen', 'No', 90, 1]]
I want to ask for the low and higher value for tlist[2]我想询问 tlist[2] 的低值和高值
low = int(input("Enter low")) #take this as 1
high = int(input("Enter High")) #take this as 50
this need to be updated and when I call the list again it should show, and remove 'zen' from the list这需要更新,当我再次调用列表时它应该显示,并从列表中删除“zen”
tlist = [['Josh', 'Yes', 1, 4], ['Amy', 'No', 30, 4]]
You can use this code.您可以使用此代码。 Try to iterate over the list with condition including low and high
尝试使用包括低和高的条件迭代列表
tlist = [['Josh', 'Yes', 1, 4], ['Amy', 'No', 30, 4], ['Zen', 'No', 90, 1]]
low = int(input("Enter low")) #take this as 1
high = int(input("Enter High")) #take this as 50
tlist = [l for l in tlist if l[2]>=low and l[2]<=high]
print(tlist)
tlist
unchanged and saving result to another list.tlist
不变,并将结果保存到另一个列表。t_list
t_list
中的每个内部列表[low,high]
.[low,high]
范围内。
tlist = [['Foo', 'No', 80, 1], ['Bar', 'No', 90, 1], ['Josh', 'Yes', 1, 4], ['Amy', 'No', 30, 4], ['Zen', 'No', 90, 1]]
updated_list = []
low = 1
high = 50
for inner_list in tlist:
if inner_list[2] >= low and inner_list[2] <= high:
updated_list.append(inner_list)
print(updated_list)
# [['Josh', 'Yes', 1, 4], ['Amy', 'No', 30, 4]]
tlist
tlist
tlist = [['Josh', 'Yes', 1, 4], ['Amy', 'No', 30, 4], ['Zen', 'No', 90, 1]]
low = 1
high = 50
for i in range(len(tlist)-1,-1,-1):
inner_list = tlist[i]
if inner_list[2] < low or inner_list[2] > high:
tlist.remove(inner_list)
print(tlist)
# [['Josh', 'Yes', 1, 4], ['Amy', 'No', 30, 4]]
When tlist = [['Foo', 'No', 80, 1], ['Bar', 'No', 90, 1], ['Josh', 'Yes', 1, 4], ['Amy', 'No', 30, 4], ['Zen', 'No', 90, 1]]
, output is :当
tlist = [['Foo', 'No', 80, 1], ['Bar', 'No', 90, 1], ['Josh', 'Yes', 1, 4], ['Amy', 'No', 30, 4], ['Zen', 'No', 90, 1]]
,输出为:
[['Josh', 'Yes', 1, 4], ['Amy', 'No', 30, 4]]
Note : The concern expressed in the comments has been resolved by iterating from the end of the list instead of the beginning.注意:评论中表达的担忧已通过从列表末尾而不是开头迭代来解决。 The re-indexing caused by
remove()
no longer affects the final answer.由
remove()
引起的重新索引不再影响最终答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.