List.remove(x)不在列表中?如何从数组中删除对象?

时间:2018-03-26 20:51:29

标签: python random

我正在尝试制作一个程序,为项目每天随机分配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_array的相同代码复制到lele-澄清,以便每天分配2个生物学主题和2个化学主题。 然而,在我得到那么远的list.remove(x)错误出现之前!任何关于如何随机选择字符串项然后从列表中删除它们的方法将非常有用thnx。

本。

1 个答案:

答案 0 :(得分:0)

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)

然后列表删除将起作用,因为它们是2个不同的元素。

len(sting_array) < 2

突破你的循环