简体   繁体   English

如何获取嵌套列表范围内的元素

[英]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)

Method 1 : Keeping tlist unchanged and saving result to another list.方法 1:保持tlist不变,并将结果保存到另一个列表。

  • Loop through each inner list in t_list循环遍历t_list中的每个内部列表
  • Access the third element at index 2 in each inner list.访问每个内部列表中索引 2 处的第三个元素。
  • Check if this element in the range [low,high] .检查此元素是否在[low,high]范围内。
  • If yes, add current inner list to new list.如果是,则将当前内部列表添加到新列表中。

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]]

Method 2 : Using remove() to directly modify tlist方法二:使用remove()直接修改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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM