[英]How do I print lists side by side in Python?
新用户练习列表和循环。 我的目标是从我自己的输入中创建两个列表(范围为 2 以进行快速测试,但希望达到 10)。 我在两个问题上遇到了困难:
名字 \t\t\t $77
下一个名字 \t\t\t $16
我的代码:
list1 = []
list2 = []
count = 0
for i in range(2):
customers = input("Customers name? ")
list1.append(customers)
spent = float(input("Amount spent? "))
list2.append(spent)
count += spent
averageSpent = count / 2 # change this when changing range
print("Name\t\t\tAmount")
# won't print side by side. how to use zip()?
print((*list1 + list2), sep = "\n")
print("Total spending:\t\t $", count)
print("Average spending:\t $", averageSpent)
# keep getting 'object is not iterable'
#print("Most money spent:\t $", max(spent))
#print("Least money spent:\t $", min(spent))
我的 output 目前是:
客户姓名? 工作
花费金额? 45
客户姓名? 请
花费金额? 65
名称 金额
工作
请
45.0
65.0
总支出:$ 110.0
平均消费:55.0 美元
谢谢!
并排打印的东西在这里得到回答: 并排打印 2 个列表
关于 float 或 int 不可迭代的错误是因为您调用的是max(spent)
而不是max(list2)
。 function max()
需要一个列表或其他可迭代的 object。
关于您遇到的第一个问题,并排打印 output 的最佳方法是遍历列表并打印列表中的每个值。 除此之外,您还可以使用 f-strings,这是我们在 python 3.6 中添加的一项功能,它允许您执行以下操作:
x = 10
print(f'{x+20}')
>> 30
您可以 在此处阅读有关 f 字符串的更多信息。
关于您面临的第二个问题。 您收到此错误是因为您在单个浮点数上调用 max() function。 应调用最大 function 以获得列表。
我做了一些调整。 这是最终代码的样子:
list1 , list2 = [] , []
max_range = 2
count = 0
for i in range(max_range):
customer_name = input("Customer name: ")
list1.append(customer_name)
spent = float(input("Amount Spent: "))
list2.append(spent)
count += spent
averageSpent = count / max_range
print("Name\t\t\tAmount")
for i in range(len(list1)):
print(f'{list1[i]} \t\t\t$ {list2[i]}')
print("Total spending:\t\t $", count)
print("Average spending:\t $", averageSpent)
print("Most money spent:\t $", max(list2))
print("Least money spent:\t $", min(list2))
编辑:使用 zip function 可能是使用元组并排打印两个输出的另一种选择。 但是,由于您已经说过您对这些主题不熟悉,我认为您应该远离 zip(暂时),直到您对列表感到满意为止。
bikemule 关于迭代是正确的。 您需要使用列表而不是单个号码来调用max
。 ( max(101)
会返回什么?这不太合理。)
要使两个列表并排显示,您可以将zip
与for
循环结合使用。 它将列表转换为元组集,然后在打印时以几乎表格的格式出现。
list_a = [1, 2, 3]
list_b = [4, 5, 6]
for col_a, col_b in zip(list_a, list_b):
print("A_Item: %s | B_Item: %d" %(col_a, col_b))
回报:
A_Item: 1 | B_Item: 4
A_Item: 2 | B_Item: 5
A_Item: 3 | B_Item: 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.