Проверка длины списков и печать имени самого длинного и самого короткого списков в Python - PullRequest
0 голосов
/ 08 апреля 2020

Эй, у меня есть проект, в котором я генерирую случайные числа от 1 до 4 49 раз и добавляю их в список. Предполагается, что эти цифры представляют цвет смарт-ie. Затем мне пришлось разделить результаты этого списка на собственные списки, что мне также удалось сделать. Но теперь он хочет, чтобы я сравнил эти списки по длине и распечатал название самого длинного и самого короткого списка. (Какой цвет имеет больше всего, а какой цвет меньше всего.) Вот что я пробовал. Я не уверен, как go об этом действительно.



list = open('list.txt', 'w')
fields = None
redList = []
blueList = []
yellowList = []
greenList = []
biggestList = 0
smallestList = 0

for count in range(49):
    randNum = random.randint(1, 4)
    if randNum == 1:
        smartyColor = 'Red'
        list.write('1 ')

    elif randNum == 2:
        smartyColor = 'Blue'
        list.write('2 ')

    elif randNum == 3:
        smartyColor = 'Green'
        list.write('3 ')

    elif randNum == 4:
        smartyColor = 'Yellow'
        list.write('4 ')

list.close()

list = open('list.txt', 'r')
for line in list:
    fields = line.split()
for field in fields:
    if field == '1':
        redList.append(field)
    elif field == '2':
        blueList.append(field)
    elif field == '3':
        greenList.append(field)
    elif field == '4':
        yellowList.append(field)

if redList == blueList:
    print("There are as many red smarties as blue smarties.")
elif redList  == greenList:
    print("There are as many red smarties as green smarties.")
elif redList == yellowList:
    print("There are as may red smarties as yellow smarties.")

if blueList == greenList:
    print("There are as many blue smarties as there are green smarties.")
elif blueList == yellowList:
    print("There are as many blue smarties as yellow smarties.")

if greenList == yellowList:
    print("There are as many green smarties as there are yellow smarties.")

if redList > biggestList:
    biggestList = redList
elif blueList > biggestList:
    biggestList = blueList
elif greenList > biggestList:
    biggestList = greenList
else:
    biggestList = yellowList

print("The biggest list was ",biggestList,"." )

if redList < smallestList:
    smallestList = redList.Length
elif blueList < smallestList:
    smallestList = blueList
elif greenList < smallestList:
   smallestList = greenList
else:
   smallestList = yellowList

print("The smallest list was ",smallestList,"." )

Ответы [ 3 ]

0 голосов
/ 08 апреля 2020

Ваш вопрос по сути:

Учитывая кучу списков, как мне распечатать самый маленький и самый большой из них (по размеру)?

Здесь Вы go:

def print_biggest_and_smallest(mylists):
    mylists.sort(key = lambda x:len(x))
    smallest = mylists[0]
    biggest = mylists[-1]
    print(smallest, biggest)
0 голосов
/ 08 апреля 2020
l = []
for i in range(49):
    l.append(random.randint(1,4))

colors = [[],[],[],[]]
for i in l:
        colors[int(i)-1].append(i)

length_colors= [len(i) for i in colors]
min, max = 0,0

for i in range(1,len(colors)):
    if length_colors[min] > length_colors[i]:
        min = i
    elif length_colors[max] < length_colors[i]:
        max = i

print(length_colors)
print("Biggest list = ", colors[max], ",with ", length_colors[max], " elements")
print("Smallest list = ", colors[min], "with ", length_colors[min], " elements")

Было бы полезно, если бы вы могли использовать numpy, тогда вы могли бы просто использовать np.argmax / np.argmin.

0 голосов
/ 08 апреля 2020

Вы не можете использовать> с 2 списками, вам нужно сделать следующее:

Где у вас есть:

if list_a > list_b:

Заменить на:

if len(list_a)>len(list_b):
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...