Python 2d数组问题

2024-04-25 07:14:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了一个列表,每个列表包含一个数字1、2、3和0(0重复两次)。取决于数字和位置,我想一个相应的变量得到增加1次,每次发生。你知道吗

    ballots = [['1', '2', '3', '0', '0'], 
    ['1', '3', '0', '2', '0'], 
    ['1', '2', '3', '0', '0'], 
    ['0', '3', '2', '0', '1'],  
    ['1', '3', '0', '2', '0'],  
    ['2', '0', '3', '1', '0'],  
    ['0', '0', '2', '1', '3'],  
    ['0', '1', '2', '3', '0'],  
    ['0', '1', '0', '2', '3'],  
    ['2', '3', '1', '0', '0'],  
    ['3', '2', '0', '0', '1'],  
    ['0', '1', '3', '2', '0'],  
    ['0', '0', '1', '2', '3'],  
    ['0', '0', '3', '2', '1'],  
    ['1', '2', '3', '0', '0'],  
    ['2', '1', '3', '0', '0'],  
    ['0', '3', '2', '1', '0'],  
    ['0', '2', '3', '0', '1'],  
    ['1', '2', '3', '0', '0'],  
    ['1', '0', '0', '3', '2'],  
    ['2', '1', '3', '0', '0'],  
    ['3', '1', '2', '0', '0'],  
    ['2', '3', '0', '1', '0'],  
    ['0', '0', '3', '1', '2'],  
    ['0', '3', '1', '0', '2'],  
    ['2', '1', '0', '0', '3'],  
    ['2', '0', '0', '1', '3'],  
    ['2', '0', '0', '1', '3'],  
    ['3', '0', '1', '0', '2']]

例如,对于第一个列表:

  • 位置1中的1意味着candidate1vote1 += 1
  • 第二个位置的2意味着candidate2vote2 += 1
  • 第3位的3表示candidate3vote3 += 1

所有0都被忽略,但仍算作一个空格。对于第二个列表:

  • 第一个位置的1意味着candidate1vote1 += 1
  • 第二位的3表示candidate3vote2 += 1
  • 第4位的2表示candidate4vote2 += 1

基本上,位置对应于候选人1/2/3/4/5,值对应于第一优先票、第二优先票或第三优先票。你知道吗

有人知道我是如何使用for/while循环对列表进行排序的吗?这样就可以通过每个投票和每个单独的投票进行相应的求和?你知道吗


Tags: 列表for排序数字投票空格while候选人
2条回答

这样,您就可以将每个答案列在一个列表中:

c1= list()
c2= list()
...

for i in ballots:
    c1.append(i[0])
    c2.append(i[1])
    ...

首先我想澄清一下。。所以你不仅要收集每个候选人的选票,还要收集每个候选人的偏好向量选票(1,2,3)?你知道吗

  1. 了解您正在处理的嵌套列表以及如何为它们编制索引。(您可以在numpy库中使用这些类型的术语数组)
  2. 索引列表时,从外到内访问数据。e、 g.[outer][inner](outer/inner,因为可能有两个以上的嵌套列表)

既然您知道这一点,考虑到您没有内存/时间限制,而且您似乎对python不太熟悉,我建议您使用double for loop。让我们创建一个带有首选项的候选人嵌套列表。它们的外部索引将是候选#,内部优先列表。你知道吗

len(ballot)给你行的#(为了方便起见)5,你已经有了列的#。请算出缩进。。你知道吗

candidate = [[0]*4 for n in xrange(5)] //depends on your choice - whether you want to count for number of 0s, if you want to match position and preference..
n = len(ballot)
for i in range(0, n): //python index starts with 0, if you use range it includes the start number but not the last. google if you don't know
    for j in range(0, 5):
        if ballots[i][j] == '1':
            candidate[j][1] +=1
        elif ballots[i][j] == '2':
            candidate[j][2] +=1
        elif ballots[i][j] == '3':
            candidate[j][3] +=1
        else: //0
            candidate[j][0] +=1

相关问题 更多 >

    热门问题