Ask Your Question
0

Removing some element of a list according to the zero of another

asked 2020-06-01 15:38:49 +0200

Cyrille gravatar image

updated 2020-06-02 09:48:06 +0200

slelievre gravatar image

I have the following code.

candidats = 4  # nombre de candidats
Pref = Arrangements(["a", "b", "c", "d"], candidats).list()
show(Pref)
show(LatexExpr("Nombre~de~préférences~possibles~="+latex(len(Pref))))
elec = 100
candidats = 4
nn = list([i for i in range(len(Pref))])
ZZ = IntegerRing()
PP = ([0 for i in nn])
PP[0] = ZZ.random_element(0, elec)
for k in nn:
    PP[k] = ZZ.random_element(0, elec - sum(PP[j] for j in nn[:k]))
PP[len(Pref) - 1] = (PP[len(Pref) - 1] if (elec - sum(PP)) == 0 
                     else  PP[len(Pref) - 1] + (elec - sum(PP)))
import random
PP1 = random.sample(PP, len(PP))
show(sum(PP))
show(PP)
show(PP1)
show(Pref)
def rz(l1, l2):
    for k in range(len(l1)):
        if l1[k] == 0:
            del(l2[k])
show([len(PP), len(Pref)])
show(rz(PP, Pref))

The problem here begins with def rz... I would like to delete the elements of the lists Pref and PP at indices where the list PP has zeros. But it doesn't work. I do not find my error. I was also wondering if it could be done by embedding "two list comprehensions".

edit retag flag offensive close merge delete

Comments

How is Pref defined ?

tmonteil gravatar imagetmonteil ( 2020-06-01 15:51:48 +0200 )edit

I have repeared my oversight.

Cyrille gravatar imageCyrille ( 2020-06-01 23:22:31 +0200 )edit

1 Answer

Sort by » oldest newest most voted
0

answered 2020-06-01 18:12:16 +0200

FrédéricC gravatar image

Like this

def remove_zero(l1, l2):
     return [z1 for z1, z2 in zip(l1, l2) if z2]
edit flag offensive delete link more

Comments

Sorry but I do not understand you suggestion. I understand the meaning of zip but not the idea --- where is the condition. + SM said that zip is not scriptable.

Cyrille gravatar imageCyrille ( 2020-06-02 12:43:25 +0200 )edit

C'est littéralement la liste des z1 dans l1 tels que l'élément z2 correspondant dans l2 soit non nul. La condition est à la fin ; j'aurais pu écrire "if z2 != 0" mais j'ai utilisé une forme équivalente abrégée.

FrédéricC gravatar imageFrédéricC ( 2020-06-02 13:24:30 +0200 )edit

Merci FrédéricC. Mais sans z2 != 0 tous les zéros ne sont pas éliminés.

Cyrille gravatar imageCyrille ( 2020-06-02 15:31:50 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2020-06-01 15:38:49 +0200

Seen: 614 times

Last updated: Jun 02 '20