103 votes

Comment ajouter plusieurs éléments dans une ligne en Python ?

Je l'ai fait :

count = 0
i = 0
while count < len(mylist):
    if mylist[i + 1] == mylist[i + 13] and mylist[i + 2] == mylist[i + 14]:
        print mylist[i + 1], mylist[i + 2]
    newlist.append(mylist[i + 1])
    newlist.append(mylist[i + 2])
    newlist.append(mylist[i + 7])
    newlist.append(mylist[i + 8])
    newlist.append(mylist[i + 9])
    newlist.append(mylist[i + 10])
    newlist.append(mylist[i + 13])
    newlist.append(mylist[i + 14])
    newlist.append(mylist[i + 19])
    newlist.append(mylist[i + 20])
    newlist.append(mylist[i + 21])
    newlist.append(mylist[i + 22])
    count = count + 1
    i = i + 12

Je voulais faire le newlist.append() en quelques déclarations.

1voto

zakizakibzr Points 57

Utilisez une boucle for, cela pourrait ressembler à ceci :

for x in [1,2,7,8,9,10,13,14,19,20,21,22]:
    new_list.append(my_list[i + x])

0voto

Daring_T Points 76

Si vous ajoutez le même élément, vous pouvez procéder comme suit :

["a"]*2
>>> ['a', 'a']

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X