从0/1网格返回值

时间:2017-12-21 09:46:35

标签: python function random

嘿那里! 我是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]))

5 个答案:

答案 0 :(得分:1)

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

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"))

答案 1 :(得分:0)

要计算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)

答案 2 :(得分:0)

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

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

n是数组的长度 并计算在循环之前添加变量,如

countZeros =  0   
countOnes  = 0  

并在循环中添加

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

答案 3 :(得分:0)

首先,我建议使用实际的01代替'0''1'。此外,您可以对foo使用list-multiplication,为A使用list-comprehensions(但 not list-multiplications!),以使代码更清晰一些。然后,您只需获取sum的{​​{1}},然后从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 sum s。)

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

len

答案 4 :(得分:0)

亲爱的,等待漫长的等待! 我有一个朋友帮助我,这就是他想出来的:

##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]