Python 脚本根据 .csv 文件中的抽奖券生成随机获奖者 - 不断在名称末尾添加随机数字列表

问题描述 投票:0回答:1

我有一个文件,一个 .csv 文件,有两列。第一个是人的名字。第二个是他们有多少张票。

我想编写一个Python脚本来随机选择一张中奖彩票,然后匹配并返回中奖者的姓名。

我设法使脚本正常工作,但有一个问题。该程序不断在每个名称后面添加一个从 1 到 41 的巨大整数字符串,我无法弄清楚是什么原因造成的。

import csv
import random

file = open("C:\\Users\\Username\\Desktop\\raffle.csv")
type(file)
csvreader = csv.reader(file)

rows = []
for row in csvreader:
    rows.append(row)
    rows
    
file.close()

names = []
count = []

counter = 0

for x in rows:
    names.append(x[0])  # Assuming the name is in the first column
    count.append(x[1])

for x in rows:
    trigger = False
    for y in range(len(count)):
        y = str(y)
        if y == ",": 
            trigger = True
            
        if trigger == True: 
            count[counter] += y
        else:
            names[counter] += y
    counter+=1

TotalEntries = 0 # This is the total amount of entries.

count5 = 0 

print(*names)

for x in count:
    TotalEntries += int(count[count5])
    count5+1

winner = random.randint(0, TotalEntries)

countWin = 0
win = ""
countOut = 0


for x in count:
#    # Runs through the list of raffle entries
    for y in range(len(count)):
        if countWin == winner: 
           win = names[countOut]
        countWin+=1
    countOut+=1

winNum = str(winner)
print("The winner is number "+winNum+", "+win)

我希望名单上填满人们的个人名字。然而,每个名字后面都有一个数字列表,我无法弄清楚来源。我是 Python 新手,因此感谢任何提示。

jame01234567891011121314151617181920212223242526272829303132333435363738394041 nico0123456789101112131415161718192021222324 2526272829303132333435363738394041 silv01234567891011121314151617181920212223242526272829303132333435363738394041 kevy012345678 91011121314151617181920212223242526272829303132333435363738394041 Chri01234567891011121314151617181920212223242526272829303132 333435363738394041

返回的列表示例

我想要一个类似的列表

詹姆斯 尼科 银 凯维 克里斯

.csv 格式的输入文件示例 詹姆斯,18 尼科,19 银,48 凯维,23 克里斯,22

python csv random
1个回答
0
投票

我对如何根据姓名总数(CSV 中每对的姓名*ticket_count)选择随机命名感到困惑。

我想你的输入 CSV 看起来像这样:

Name,    Ticket count
Alice,              2
Bob,                1
Charlie,            3
Dana,               2

从中我会尝试获得一袋名字,例如:

['Alice', 'Alice', 'Bob', 'Charlie', 'Charlie', 'Charlie', 'Dana', 'Dana']

这样您就可以使用标准库的 random.choice 函数:

random.choice(bag_of_names)

将 CSV 转换为名称包可能如下所示:

bag_of_names: list[str] = []

with open("input.csv", newline="", encoding="utf-8") as f:
    reader = csv.reader(f, skipinitialspace=True)
    next(reader)  # discard header

    for row in reader:
        name = row[0]
        ticket_ct = int(row[1])

        bag_of_names.extend([name] * ticket_ct)

运行 1_000 个选择,看起来选择正确:

from collections import Counter
from typing import Counter

X = 1_000

c: Counter[str] = Counter()
for _ in range(X):
    c[pick_winner()] += 1

for name, wins in c.most_common():
    print(f"{name:<10} {(wins/X):.2%}")
Charlie    38.80%
Alice      25.40%
Dana       24.20%
Bob        11.60%
© www.soinside.com 2019 - 2024. All rights reserved.