Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k 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 Answer

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...