在Python中使用列表或数组?

2024-09-30 00:38:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要存储6个项目的信息以及它们各自的长度、宽度和成本值,然后根据用户输入计算出一些值。你知道吗

在jcusick的帮助下,我现在有了下面的代码。你知道吗

我现在需要有关注释(#)中标记的项目的帮助。你知道吗

您不需要编写完整的代码-指向正确的方向是完美的。你知道吗

到目前为止,我已经:

cost = {}
cost['Themon'] = 450
cost['Larrec'] = 700
cost['Medrec'] = 500
cost['Parallel'] = 825
cost['Suncatch'] = 400
cost['Chantran'] = 975

length = {}
length['Themon'] = 3.2
length['Larrec'] = 3.4
length['Medrec'] = 2.1
length['Parallel'] = 5
length['Suncatch'] = 3
length['Chantran'] = 9

width = {}
width['Themon'] = 2.3
width['Larrec'] = 3
width['Medrec'] = 2
width['Parallel'] = 4
width['Suncatch'] = 3
width['Chantran'] = 6

area = {}
area['Themon'] = 1 # how do i calculate the area (l*w) by referencing the lenght and width dictionary 
area['Larrec'] = 1
area['Medrec'] = 1
area['Parallel'] = 1
area['Suncatch'] = 1
area['Chantran'] = 1

#menu
ans=True
while ans:
    print("""
    Enter 1. to find cheapest garden deck 
    Enter 2. to display the names of garden decks over a certain lenght
    Enter 3. to display the number of garden decks that are available over a certain area
    Enter 4. to quit
    """)
    ans=input("What option would you like? ")
    if ans=="1":
        print (min(cost, key=cost.get))
    elif ans=="2":
        input_length = input("\n Please enter minimum deck length between 2 and 15 metres")
        print # i need to display names of the decks greater than the user input length
    elif ans=="3":
        input_area = input("\n Please enter deck area in metres squared between 4 and 80")
        print # i need to display the number of garden decks that are greater that the user input area
    elif ans=="4":
        print("\n Thank you for using Penny's Decking")
    else:
        print("\n Not a valid choice")

Tags: thetoinputparallelareawidthlengthprint
3条回答

我认为熊猫对这样一小段代码来说可能是杀伤力过大了。对于您的特定示例,阵列将是一种更快的存储方法。不过,我甚至想说,列表可能是处理这种特殊规模的更具python风格的方法。在这两种情况下,您的性能都不会受到太大的影响,而且它现在的可读性比使用数组要好一些。你知道吗

为了进一步阅读,有时namedtuple在您保存和访问记录的大型示例中会有所帮助: https://docs.python.org/3/library/collections.html#collections.namedtuple

我建议您研究Pandas,并更具体地使用数据帧来实现这一点,因为它们非常适合您所做的事情。就像其他人提到的。确保缩进格式正确。如果你不想使用数据帧的话,那么我认为这些数据帧非常适合你的工作。我建议创建一个价值观词典并引用它们。你知道吗

我可以考虑为您感兴趣的每个变量(长度、宽度、成本)创建一个dictionary。然后,您可以根据用户的回答查询特定词典:

cost = {}
cost['Themon'] = 450
cost['Larrec'] = 700
...
print (min(cost, key=cost.get))
# 'Themon'

相关问题 更多 >

    热门问题