简体   繁体   中英

How do I make a 5x5 list?

I tried with for loops, but I just get 5 1 2 1 1 4 1 2 2 4 2 1 5 2 4 5 4 2 3 2 4 5 3 2 3 instead of an actual 5x5 grid. (just so you know the context:I am later supposed to create a dictionary whose keys are the random numbers from 5x5 list and whose values are the how many times the number occurs and then print the three most common numbers.)

from random import randint
for i in range(1,6):
    for j in range(1,6):
            print("{:3d}".format(randint(1,5)),end=" ")

Simple to use list comprehension to create 5x5 list

from random import randint
n = 5
grid = [[randint(1, 5) for _ in range(n)] for i in range(n)]

print(grid)

Output

[[5, 3, 3, 5, 5], [3, 2, 4, 3, 3], [3, 3, 3, 3, 4], [3, 4, 5, 3, 3], [5, 4, 1, 2, 3]]

Explanation

We're creating a list of lists

Create an inner nested list of n elements (inner for loop)

[randint(1, 5) for _ in range(n)]

Stack the inner lists (looping over i)

[[...] for i in range(n)]
import random
import itertools
import operator
five_dim = [[random.randint(1,5) for b in range(0,5)]for a in range(0,5)]
flat_list = [num for num in itertools.chain(*five_dim)]
key_set = set(flat_list)
freq_dict ={k: flat_list.count(k) for k in key_set}
x= sorted(freq_dict.items(), key = operator.itemgetter(0))[0:3]
print(x)

Steps:-

  1. First create 5 X 5 grid
  2. Create flatten list from the list of lists(5 x 5 grid)
  3. Create a dictionary, set of random numbers from the grid as a key and frequency of each number as value
  4. Sort the dictionary value in ascending order and return the three most frequent one, as a list of tuple, (key, value) pair.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM