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
2.3k views
in Technique[技术] by (71.8m points)

python - Add a maximum of 200 elements on en empty 2D list

I am having a Python program that creates lists of 3 elements.

['a', 'was', 'mother']

and adds them on an empty list,

output_text=[]
while True:
    candidates = [t for t in lines if t[0:2] == last_two]
    if not candidates:
        break
    
    triplet = random.choice(candidates)
    last_two = triplet[1:3]
    output_text.append(triplet)
    print('
 Επιλογ? Matching Τρι?δα?: 
',triplet)
    print('
 Δ?ο Τελευτα?ε? Λ?ξει? Matching Τρι?δα?: 
',last_two)
    print(output_text)

I want to create an if statement that keeps adding the 3-element lists to output_text until 200 words (total elements) are being stored.

Any ideas?


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

1 Reply

0 votes
by (71.8m points)

You could e.g. combine itertools.cycle and .islice, or just use modulo %:

>>> from itertools import islice, cycle                                     
>>> lst = ['a', 'was', 'mother']                                            
>>> list(islice(cycle(lst), 10))                                            
['a', 'was', 'mother', 'a', 'was', 'mother', 'a', 'was', 'mother', 'a']
>>> [lst[i % len(lst)] for i in range(10)]                                 
['a', 'was', 'mother', 'a', 'was', 'mother', 'a', 'was', 'mother', 'a']

(Technically, this does not append to an empty list but creates the list in one go, but I assume that's okay.)


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

...