简体   繁体   中英

how to loop infinite times by repeating same elements with single list in python

I am trying this and getting Memory error.

A = [a,b,c,d]
for i,j in zip(cycle(A), itertools.count()):
    print (i+str(j))

how can i print this output:

[a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3 .. infinite times]

You're on Python 2.7, and zip tries to create a list from an inexhaustible iterator; your memory simply blows up. Use itertools.izip instead.

Here is how you could proceed: ( I added a break from the loop after 10000, you can remove it to get to infinity and beyond)

import itertools

A = ['a', 'b', 'c', 'd']
for idx, letter in enumerate (itertools.cycle(A)):
    print(letter + str(idx), end=' ')

    if idx == 10000:
        break

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