Python脚本,用于根据.csv文件中的抽奖券生成随机赢家-不断将随机数字列表添加到名称的末尾

fjaof16o  于 10个月前  发布在  Python
关注(0)|答案(1)|浏览(125)

我有一个文件,一个.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 nico01234567891011121314151617181920212223242526272829303132333435363738394041 silv01234567891011121314151617181920212223242526272829303132333435363738394041 kevy01234567891011121314151617181920212223242526272829303132333435363738394041 2019 - 11 - 22 01:00:00
返回的列表示例
我想要一份清单,
jame nico silv kevy Chri
.csv中的输入文件示例jame,18 nico,19 silv,48 kevy,23 Chri,22

xdyibdwo

xdyibdwo1#

我很困惑,你是如何根据名字的总数(CSV中每对名字的名字 *ticket_count)随机挑选一个名字的。
给定此输入CSV:

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

字符串
从那里我会尝试得到一个 * 包的名字 * 像:

['Alice', 'Alice', 'Alice', 'Bob', 'Bob', 'Charlie', 'Charlie', 'Charlie', 'Charlie', '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    40.40%
Alice      28.20%
Bob        21.30%
Dana       10.10%

的字符串

相关问题