迭代Python 2D列表以查找值(Iterating over a Python 2D list to find the value)

编程入门 行业动态 更新时间:2024-10-27 15:16:45
迭代Python 2D列表以查找值(Iterating over a Python 2D list to find the value)

我试图迭代Python 2D列表。 当算法迭代列表时, 它会将密钥添加到新列表,直到检测到新值 。 然后将操作应用于列表,然后清空列表,以便可以再次使用它,如下所示:

original_list = [('4', 'a'), ('3', 'a'), ('2', 'a'), ('1', 'b'), ('6', 'b')]

当算法读取original_list时,它应该评估每个对象的第二个值并解密它是否与前一个值不同; 如果没有,请将其添加到临时列表中。

这是psedo代码

temp_list = [] new_value = original_list[0][1] #find the first value for key, value in original_list: if value != new_value: temp_list.append(new_value)

应输出

temp_list = ['4', '3', '2']

I am trying to iterate over a Python 2D list. As the algorithm iterates over the list, it will add the key to a new list until a new value is detected. An operation is then applied to the list and then the list is emptied so that it can be used again as follows:

original_list = [('4', 'a'), ('3', 'a'), ('2', 'a'), ('1', 'b'), ('6', 'b')]

When the original_list is read by the algorithm it should evaluate the second value of each object and decipher if it is different from the previous value; if not, add it to a temporary list.

Here is the psedo code

temp_list = [] new_value = original_list[0][1] #find the first value for key, value in original_list: if value != new_value: temp_list.append(new_value)

Should output

temp_list = ['4', '3', '2']

最满意答案

temp_list = [] prev_value = original_list[0][1] for key, value in original_list: if value == prev_value: temp_list.append(key) else: do_something(temp_list) print temp_list temp_list = [key] prev_value = value do_something(temp_list) print temp_list # prints ['4', '3', '2'] # prints ['1', '6'] temp_list = [] prev_value = original_list[0][1] for key, value in original_list: if value == prev_value: temp_list.append(key) else: do_something(temp_list) print temp_list temp_list = [key] prev_value = value do_something(temp_list) print temp_list # prints ['4', '3', '2'] # prints ['1', '6']

更多推荐

本文发布于:2023-08-02 08:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1372166.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:迭代   列表   Python   find   Iterating

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!