简体   繁体   中英

Appending lists to a list

I have a list I3 . I am performing an index operation through I4 and appending based on the length of I3 . The current and expected outputs are presented.

I3 = [[(0, 0), (0, 1)], [(0, 0), (1, 0)], [(0, 1), (1, 1)], [(1, 0), (1, 1)]]

for t in range(0,len(I3)):
    I4 = [(j, -i) for i, j in I3[t]]
    I4.append(I4)
    print("I4 =",I4)

The current output is:

I4 = [(0, 0), (1, 0), [...]]
I4 = [(0, 0), (0, -1), [...]]
I4 = [(1, 0), (1, -1), [...]]
I4 = [(0, -1), (1, -1), [...]]

The expected output is:

I4 = [[(0, 0), (1, 0)],[(0, 0), (0, -1)],[(1, 0), (1, -1)],[(0, -1), (1, -1)]]

Note I4.append(I4) and I4 = [(0, 0), (1, 0), [...]] . You're appending a list to the end of itself. That's recursive. Try to append it to an empty list.

I3 = [[(0, 0), (0, 1)], [(0, 0), (1, 0)], [(0, 1), (1, 1)], [(1, 0), (1, 1)]]

temp = []
for t in range(0,len(I3)):
    I4 = [(j, -i) for i, j in I3[t]]
    temp.append(I4)
    print("I4 =",temp)

results in

I4 = [[(0, 0), (1, 0)]]
I4 = [[(0, 0), (1, 0)], [(0, 0), (0, -1)]]
I4 = [[(0, 0), (1, 0)], [(0, 0), (0, -1)], [(1, 0), (1, -1)]]
I4 = [[(0, 0), (1, 0)], [(0, 0), (0, -1)], [(1, 0), (1, -1)], [(0, -1), (1, -1)]]

这是一个班轮

I4 = [[(j, -i), (l, -k)] for (i, j), (k, l) in I3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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