【问题标题】:Returning Value from 0/1 Grid从 0/1 网格返回值
【发布时间】:2017-12-21 09:46:35
【问题描述】:

你好! 我是 Python 和一般编程的新手。我找到了一种打印随机 0 和 1 网格的方法。我需要保存这些网格并计算其中 0 的数量。这是我到目前为止所拥有的:(我使用的是 Python 2.7)

import random
foo = ['0', '0', '0', '1', '1']
x = random.choice(foo)
A = [[random.choice(foo), random.choice(foo), random.choice(foo), random.choice(foo)],
[random.choice(foo), random.choice(foo), random.choice(foo), random.choice(foo)],
        [random.choice(foo), random.choice(foo), random.choice(foo), random.choice(foo)],
        [random.choice(foo), random.choice(foo), random.choice(foo), random.choice(foo)],
        [random.choice(foo), random.choice(foo), random.choice(foo), random.choice(foo)]]


print('\n'.join([''.join(['{:4}'.format(item) for item in row]) 
          for row in A]))

【问题讨论】:

  • 您的问题是什么?如果您希望人们对此提出建设性的批评,代码审查就是您的去处。
  • 为什么不让foo 成为[0, 1] 的列表?
  • 提示:查看for循环
  • @cᴏʟᴅsᴘᴇᴇᴅ 因为他们希望'0' 有 60% 的概率。
  • @COLDSPEED 因为我可能需要一定比例的0和1s

标签: python function random


【解决方案1】:

要计算矩阵中'0's 的数量,您可以这样做:

sum(sum(x == '0' for x in r) for r in A)

要生成矩阵,你可以自己省一些代码来做

A = [[random.choice(foo) for _ in range(4)] for __ in range(5)]

如果您仍然想存储字符串表示形式,还有一种更易于阅读的方式:

s = '\n'.join([''.join(['{:4}'.format(item) for item in row]) 
          for row in A])
print(s)
print(s.count("0"))

【讨论】:

    【解决方案2】:

    要计算 0 的数量,您可以使用它

    count0s = [item for sublist in A for item in sublist].count('0')
    

    要存储网格,您可以使用列表并附加到它。像这样:

    gridList = []
    grid = '\n'.join([''.join(['{:4}'.format(item) for item in row]) 
      for row in A])
    gridList.append(grid)
    

    【讨论】:

    • 谢谢!我没有你们那么快。我将审查您的所有选项并尝试使用最好的并尽快发布更新!
    【解决方案3】:

    我建议添加一个 for 循环。要获得相同的结果,请这样做

    for i in range(n):   
       A[i] = radom.choice(foo)   
    

    n 是数组的长度 并在循环之前添加一个变量,例如

    countZeros =  0   
    countOnes  = 0  
    

    并在循环中添加

    if  a == 0:   
        countZeros++  
    else:   
        countOnes++  
    

    【讨论】:

    • 小心,增量在 Python 中不像那样工作。
    • 这只是无效的语法。
    【解决方案4】:

    首先,我建议使用实际的01 而不是'0''1'。此外,您可以对foo 使用列表乘法,对A 使用列表理解(但不是列表乘法!)以使代码更清晰。然后,您可以得到sums 中的sum,然后从A 中的元素总数中减去它。

    >>> foo = [0] * 3 + [1] * 2
    >>> A = [[random.choice(foo) for _ in range(4)] for _ in range(5)]
    >>> A
    [[0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1], [0, 1, 1, 0], [1, 0, 1, 0]]
    >>> sum(map(len, A)) - sum(map(sum, A))
    12
    

    (当然,如果你知道A的尺寸,你就不必sumlens。)

    或者使用collections.Counter(也适用于字符串):

    >>> collections.Counter(x for a in A for x in a)
    Counter({0: 12, 1: 8})
    

    【讨论】:

      【解决方案5】:

      亲爱的,久等了! 我有一个朋友帮助我,这是他想出的:

      ##Printing the Grid##
      import random
      import numpy as np
      from numpy import random as nprand
      
      def create_matrix():
        # determine the random number of ones and zeros to be put into the lists
        c0_min = 20 # minimal number of zeros
        c0_var = 5 # range of possible additional zeros
        c0 = int(nprand.rand()*c0_var + c0_min) # count of zeros
      
        c1_min = 20 # ones
        c1_var = 20 
        c1 = int(nprand.rand()*c1_var + c1_min) # count of zeros
      
        # construct a long list with ones and zeros of random order
        # items
        items = [0,]*c0 + [1,]*c1
        random.shuffle(items)
      
        # determine the length of the rows 1-4
        # there is a minimal length + a variable length
        # len of rows
        lmin = 10
        rowcount = 4
        spacemax = 5
      
        # determine the number of characters that are freely assignable (total number minus minimal length)
        l_temp = c0+c1-lmin*rowcount # variable assignable characters
      
        # divide residual characters with respect to random weights among the rows
        l_weights = nprand.rand(4)
        l_weights = l_temp*l_weights/sum(l_weights)
        s_count = nprand.randint(0,spacemax,4)
      
        # calculate the final lengths of the rows
        r1 = lmin + int(l_weights[0])
        r2 = lmin + int(l_weights[1])
        r3 = lmin + int(l_weights[2])
        r4 = lmin + int(l_weights[3])
      
        # construct the strings by iterating the previously shuffled character list
        s1 = ''.join([str(i) for i in [' ', ]*s_count[0] + items[:r1]])
        s2 = ''.join([str(i) for i in [' ', ]*s_count[1] +  items[r1:(r1+r2)]])
        s3 = ''.join([str(i) for i in [' ', ]*s_count[2] +  items[(r1+r2):(r1+r2+r3)]])
        s4 = ''.join([str(i) for i in [' ', ]*s_count[3] +  items[(r1+r2+r3):]])
      
        # return row 1-4, number of zeros, number of ones.
        return (s1, s2, s3, s4, c0, c1)
      
      m = create_matrix()
      print m[0]
      print m[1]
      print m[2]
      print m[3]
      print m[4], m[5]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-05
        • 1970-01-01
        • 1970-01-01
        • 2017-04-03
        • 1970-01-01
        • 2021-07-12
        • 2014-05-16
        • 1970-01-01
        相关资源
        最近更新 更多