如何在python和索引中处理不同大小的列表(列表索引)

时间:2018-12-04 20:00:22

标签: python list

我正在编写python脚本,并对一些与列表相关的逻辑感到困惑。 我有2个列表奖项列表,其中包含奖励元素,以及一个获奖者列表,其中包含获奖者元素。 我想为winnerList中的每个元素关联一个奖赏元素。

我有两种方法:包含此逻辑的DistributionPrizes和从DistributionPrizes方法调用的sendEmail方法。

我遇到的问题是,当每个获奖者没有足够的奖品时,脚本将在第一次检查后停止。

存在三种可能的条件: 1.获奖人数足以获奖。在这种情况下,请调用emailWinners方法。 2.奖品少于获奖者。对于每个与奖品相匹配的获奖者,请致电emailWinners。 3.没有奖品。在这种情况下,输出错误。

我不确定如何为每个与奖品匹配的获奖者调用emailWinners方法。当prizeList和winnerList大小不同时,尝试为每个获奖者调用emailWinner时,出现索引错误。

例如(winnerList [] =长度5,priestList [] =长度3。应通过电子邮件向3名获奖者发送奖品,但获取索引超出范围错误。)

这是我到目前为止尝试过的:

 if len(prizeArray) < len(winnerEmail):

    # Not enough prizes for every winner

    print("Not enough prizes for " + prizeType)  # Alert if not enough prizes

    for email in winnerEmail:
        emailUserWithPrize(winnerEmailAddress, winnerPrize)

winnerEmailAddress = ""
winnerPrize = ""
for i in range(len(winnerEmail)):

    # For every prize thats available, assign one email to it

    winnerEmailAddress = winnerEmail[i]

    # Assign an email from the list to a prize from the list

    if i < len(prizeArray):

        winnerPrize = prizeArray[i]

        prizeArray.remove(winnerPrize)

        # Write array content to prize file, essentially removing used prizes

        openFile.close()  # Should delete all content

        writeToFile = open(prizeFile, 'w')

        writeToFile.write(prizeArray[i])  # Should write remaining prizes back to file





    else:

        print("No prize available for " + winnerEmail[i])

    # print(winnerEmailAddress, " won ", winnerPrize)

    # also need to remove this entry from prize file

    emailUserWithPrize(winnerEmailAddress, winnerPrize)

2 个答案:

答案 0 :(得分:1)

您通常会使用zip函数处理类似这样的事情。例如:

import re
import random
p = re.compile(r'^\w+@\w+\.\w+$')

prizes = ['blender', 'car', 'pencils', 'tablet']
emails = ['', 'sjadhgf', 'bob@bob.com', 'jack@bob.com',
          'jenny@bob.com', 'frank@google.com', 'someone@gmail.com',
          'other@other.com', 'runner@xxx.co']

valid_emails = [e for e in emails if p.match(e)]
random.shuffle(valid_emails)

for winner, prize in zip(valid_emails, prizes):
    print(f'{prize} goes to {winner}')

答案 1 :(得分:0)

自检查以来,这是预期的行为

if len(prizeList) > len(emailList):

检查奖品列表是否大于电子邮件列表。该if语句没有else语句,因此脚本在len(prizelist) <= len(emailList)

时停止

无论是谁写的,都可能应用了此检查,以便从那时起就可以做出“每个人都有足够的奖品”的假设。