列表。是否删除不在列表中的(x)?选择对象后如何从数组中删除?

2024-09-28 23:33:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个程序,每天随机分配2个项目的主题。谁能帮我找出代码中的错误/解释一下我该怎么做

import random


x=0 
days_ahead = 30
sting_array = [ 'Respiration', 'Microbiology', 'Population size and ecosystems', 'Human Impact on the environment', 'Sexual Reproduction in humans', 'Sexual Reproduction in plants', 'Inheritance', 'Variation and evolution',
                'Application of reproduction and genetics', 'Homeostasis', 'nervous system', 'chemical elements and biological compounds', 'cell structure and organisation', 'cell membrane and transport', 'Enzymes', 'Nucleic Acids and Their functions'
                'The cell cycle and cel division', 'Classification and biodiversity', 'Adaptations for gas exchange', 'Adapt for trans animals', 'Adapt for trans plants', 'adapts for nutrition',         ]
lele = [ 'Rates of reaction', 'Equilibrium', 'Acids and Bases', 'Buffers and neutrilisation', 'Enthalpy and Entropy', 'Redox and Electrode Potentials', 'Transition Metals',
         'Periodicity', 'Enthalpy', 'Reactivity Trends', 'Reaction rates and equilibrium', 'Alkanes', 'Alkenes', 'Alcohols', 'Haloalkanes', 'Organic Synthesis', 'Aromatic Chemistry',
         'Carbonyls and Carboxylic Acids', 'Amine, aminio acid and proteins', 'Chromatography and Spectroscopy']


while x< 30:
    x+=1
    pee_pee = random.choice(sting_array)
    wee_wee= random.choice(sting_array)
    sting_array.remove(wee_wee)
    sting_array.remove(pee_pee)
    oui_oui = pee_pee + " and " + wee_wee
    print ("day " +str(x)+ " study " + (oui_oui))

if x==30:
    print ("Render complete, terminate")

我打算为乐乐的stingèu数组复制相同的代码-澄清,以便每天分配2个生物学主题和2个化学主题。 但是在我得到那个远列表之前。删除(x)错误出现了!任何关于如何随机选择字符串项,然后将它们从列表中删除的方法都非常有用


Tags: and代码主题for错误cellrandomarray
1条回答
网友
1楼 · 发布于 2024-09-28 23:33:06
pee_pee = random.choice(sting_array)
wee_wee= random.choice(sting_array)
sting_array.remove(wee_wee)
sting_array.remove(pee_pee)

在这里,同一个元素有可能被选中两次。所以第二个remove失败了。交换代码行将起作用:

pee_pee = random.choice(sting_array)
sting_array.remove(pee_pee)
wee_wee = random.choice(sting_array)  # list cannot contain pee_pee anymore
sting_array.remove(wee_wee)

或者可以使用random.sample

pee_pee,wee_wee = random.sample(sting_array,2)

然后列表删除将起作用,因为这是两个不同的元素

len(sting_array) < 2的时候,你就会跳出你的循环

相关问题 更多 >