【问题标题】:Failing to get required output from list comprehension未能从列表理解中获得所需的输出
【发布时间】:2018-03-02 06:50:54
【问题描述】:

我正在制定一项计划,以确定选举中的选票是否有效并计算选票以找出获胜者。预先警告,我对 python 和一般编码都很陌生。

目前,我正在从逗号分隔的文本文件中读取选票 - 每行都是一个选票,选票中的每张选票都需要检查其有效性,其中有效选票是任何正整数并且数量相同有候选人的票数(有 5 名候选人)。投票将被另一个函数标准化。

还有另一个函数可以将候选人姓名读入列表 - 计票时投票索引与候选人索引匹配。确定有效性的规则有一些例外,例如,该候选人的选票空白票被转换为零,超过 5 票的选票将被完全忽略。

这是读取选票的代码部分。

def getPapers(f, n):

x = f.readlines() #read f to x with \n chars
strippedPaper = [line.strip("\n") for line in x] #stores ballot without \n chars. 
print(strippedPaper)#print without \n chars
print()

strippedBallot = [item.replace(' ', '') for item in strippedPaper] #remove whitespace in ballots
print(strippedBallot) #print w/out white space
print()

#Deal with individual ballots
m = -1
for item in strippedBallot:
    m += 1
    singleBallot = [item.strip(',') for item in strippedBallot[m]]

    print(singleBallot)

getPapers(open("testfile.txt", 'r'), 5)

testfile.txt 的内容

1,2, 3, 4

,23,
9,-8
these people!
4,    ,4,4
5,5,,5,5

这是输出

#Output with whitespace.
['1,2, 3, 4 ', '', ', 23, ', '9,-8', 'these people!', '4,    ,4,4', '5,5,,5,5']

#Output with whitespace removed.
['1,2,3,4', '', ',23,', '9,-8', 'thesepeople!', '4,,4,4', '5,5,,5,5']

#Output broken into single ballots by singleBallot.
['1', '', '2', '', '3', '', '4']
[]
['', '2', '3', '']
['9', '', '-', '8']
['t', 'h', 'e', 's', 'e', 'p', 'e', 'o', 'p', 'l', 'e', '!']
['4', '', '', '4', '', '4']
['5', '', '5', '', '', '5', '', '5']

每一个投票都会被传递给另一个函数来检查有效性和规范化。问题是每张选票在输出后格式化的方式,例如 ['1,2,3,4'] 被转换为 ['1', '', '2', '', '3', '', ' 4'] - 第一个问题是如何在不创建空格的情况下从列表中删除逗号?这些空格将在检查选票时被计算在内,并且选票将被无效,因为它的选票多于候选人! (空格转换为零票)。

第二,, ['', '2', '3', ''] 需要读成 ['', '23', ''] 否则会算 0, 2 , 3, 0 而不是 0, 23, 0,最后的票数是错误的,['9', '', '-', '8'] 应该读作 ['9', '', ' -8'] 或'-','8' 将读作两票,而不是一票无效的-8。

有没有比我用来检索逗号分隔项更好的方法,它不会创建空格并错误地分解列表项?

【问题讨论】:

  • 将 testfile.txt 的内容添加到问题中。
  • 当然。我已经在输入和输出部分之间添加了它。

标签: python-3.x list iteration string-formatting list-comprehension


【解决方案1】:

假设你的输入文件如下:

-bash-4.1$ cat testfile.txt
1,2, 3, 4
, 23,
9,-8
these people!
4,    ,4,4
5,5,,5,5

你的程序稍微简化了一点:

def getPapers(f):
    x = f.readlines() #read f to x with \n chars
    strippedPaper = [line.strip("\n") for line in x] #stores ballot without \n chars. 
    print(strippedPaper)#print without \n chars
    print()

    strippedBallot = [item.split(",") for item in strippedPaper] #remove whitespace in ballots
    print(strippedBallot) #print w/out white space
    print()

    for item in strippedBallot:
        print(item)

getPapers(open("testfile.txt", 'r'))

【讨论】:

  • 这似乎有帮助,输出现在采用一种格式,可以更轻松地检查有效性。
  • @CamAtkinson 如果您找到所需内容,请将您的问题标记为已回答。
猜你喜欢
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
  • 2015-06-15
  • 1970-01-01
  • 2013-10-16
相关资源
最近更新 更多