Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

python - How can I iterate through this zipped table backwards?

I have something like this table:

table = 
[[set(), {A}, set(), {B}], 
[{c}, set(), set(), {D}]]

I want to iterate through the columns so that in order I'm looking at B, D, set(), set(), A, set(), set(), C

I flipped my table using zip(*table) and now this:

table = zip(*table)
for word_index, row in enumerate(table):
  for index in range(len(row)):
    print(row[index])

allows me to iterate like set(), C, A, set(), set(), set(), B, D Which is very close. But I want to also reverse.

zip(*table) does not allow me to call reversed(zip(*table))

How can I iterate through how I want? I don't really want to import Pandas or numpy if I can avoid it.

question from:https://stackoverflow.com/questions/65941891/how-can-i-iterate-through-this-zipped-table-backwards

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can map reversed to the rows before passing them to zip:

table = [[set(), {"A"}, set(), {"B"}], [{"c"}, set(), set(), {"D"}]]

In pairs:

for s1,s2 in zip(*map(reversed,table)):
    print(s1,s2)  

{'B'} {'D'}
set() set()
{'A'} set()
set() {'c'}

Flattened:

flat = (s for ss in zip(*map(reversed,table)) for s in ss)
print(*flat)

{'B'} {'D'} set() set() {'A'} set() set() {'c'}

Note that zip, map and reversed are all iterators so you really are iterating in the desired order (as opposed to creating reversed list for the rows or a temporary inverted matrix)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...