python - 在 Python 中检查列表的长度并打印最长和最短列表的名称
问题描述
嘿,我有一个项目,我在其中生成 1 到 4 49 次之间的随机数并将它们添加到列表中。这些数字应该代表聪明人的颜色。然后我不得不将该列表的结果分成他们自己的列表,我也设法做到了。但现在它要我按长度比较这些列表并打印出最长和最短列表的名称。(哪种颜色最多,哪种颜色最少。)这是我试过的。我真的不知道该怎么做。
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,"." )
解决方案
你的问题本质上是:
给定一堆列表,我如何打印出最小和最大的列表(按大小)?
干得好:
def print_biggest_and_smallest(mylists):
mylists.sort(key = lambda x:len(x))
smallest = mylists[0]
biggest = mylists[-1]
print(smallest, biggest)
推荐阅读
- angular - 带有 @Input() 的 Angular ExpressionChangedAfterItHasBeenCheckedError 到子视图
- android - 无法从 Android 模拟器客户端中的 python 服务器接收数据
- html - 带有 contenteditable 的 Chrome 错误和带有 display:flex 的列表
- python - 根据时间戳合并数据框中的行
- python - Python mysql参数和加载数据命令
- react-native - 当 RN 0.61 中的状态发生变化时,如何从主组件重新渲染子组件?
- terraform - 在 terraform V0.12 中连接变量
- jquery - 单击功能上的 Ajax - 不响应按钮
- c# - Xamarin 表单中的 ObservableCollection 问题
- javascript - 从类的方法返回查询结果