-1

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']
Alvaro Fuentes
  • 16,937
  • 4
  • 56
  • 68
algorhythm
  • 3,304
  • 6
  • 36
  • 56
  • 8
    So whats your question? also it would be better if you add your expected output to question! – Mazdak Apr 28 '15 at 11:13
  • [This answer explains OrderedDicts for you](http://stackoverflow.com/a/9001529/4374739) if you'd prefer to use a sortable dictionary system. – SuperBiasedMan Apr 28 '15 at 11:16
  • Just a note: Defining `new_value` as `"a"` will cause the first iteration to do something with `temp_list`, which would be empty. I suppose that's undesirable. Perhaps adding to the comparison: `if value != new_value and temp_list:`, to ensure you won't do operations with an empty list? – ODiogoSilva Apr 28 '15 at 11:18
  • What seems to be the problem? – ljk321 Apr 28 '15 at 11:25
  • You can also use a sorted dict-like type. There are many options on PyPI and elsewhere (blist, SortedCollections, sortedcontainers, rbtree, bintrees, skiplistdict...) that maintain sorted order as you mutate them (at the cost of some operations taking logarithmic rather than linear time). – abarnert Apr 28 '15 at 11:33
  • The boltons python library has a great `OrderedMultiDict`. Among other things, the "ordered" part of the dict facilitates sorting, and the "multi" part of the dict let's you invert keys and values easily. – kalefranz Apr 28 '15 at 11:35
  • Meanwhile, why are you comparing and storing the values if your desired output is the duplicate _keys_? Is that your whole problem? If so, the fix is trivial... – abarnert Apr 28 '15 at 11:35
  • @S_A: when editing, please note that inline code spans (`like this`) [shouldn't be used for highlighting](http://meta.stackoverflow.com/q/254990), only for code in sentences. Also, please try and improve the post as much as possible when editing to save the reviewers time. Thanks! – Qantas 94 Heavy Apr 29 '15 at 05:12
  • @Qantas94- Okk, I understand – Sakib Ahammed Apr 29 '15 at 05:17

3 Answers3

1
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']
Julien Spronck
  • 15,069
  • 4
  • 47
  • 55
  • 1
    From the OP's question: "An operation is then applied to the list" ... since I do not know what operation that is, I used a placeholder => `do_something()` – Julien Spronck Apr 28 '15 at 12:17
1

Not entirely sure what you are asking, but I think itertools.groupby could help:

>>> from itertools import groupby
>>> original_list = [('4', 'a'), ('3', 'a'), ('2', 'a'), ('1', 'b'), ('6', 'b')]
>>> [(zip(*group)[0], k) for k, group in groupby(original_list, key=lambda x: x[1])]
[(('4', '3', '2'), 'a'), (('1', '6'), 'b')]

What this does: It groups the items in the list by their value with key=lambda x: x[1] and gets tuples of keys corresponding to one value with (zip(*group)[0], k).

tobias_k
  • 81,265
  • 12
  • 120
  • 179
1

In case your "keys" do not repeat themselves, you could just use a defaultdict to "sort" the values based on keys, then extract what you need

from collections import defaultdict
ddict = defaultdict(list)
for v1, v2 in original_list:
    ddict[v2].append(v1)

ddict values are now all temp_list:

>>> ddict["a"]
['4', '3', '2']
Tejas Pendse
  • 551
  • 6
  • 19