迭代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']更多推荐
发布评论