【问题标题】:Changing/Adding Variables in a loop. (Python 2.7)在循环中更改/添加变量。 (Python 2.7)
【发布时间】:2014-06-16 20:47:30
【问题描述】:

我对编程真的很陌生,所以我什至不确定如何表达我的问题。我想要完成的是允许用户在几个项目中输入关于特定项目的属性,并将每个值记录到一个变量中。

例如,汽车。系统会提示用户关于汽车的三个问题:品牌、型号、年份。这个过程会循环,直到没有剩余的项目。

这就是我所拥有的:

while True:
    answer=raw_input('Is there another car? Y/N')
    if answer=Y:
        make=raw_input('Car manufacturer?')
        model=raw_input('Car Model?')
        year=raw_input('Year?')
    elif answer=N:
        break
    else:
        print 'Incorrect Response'

我知道代码确实很不稳定,但目标是每次循环通过时,它都会将用户输入记录到一组新的变量(例如,make1、model1、year1、make2、model2 等)。这样我就可以在之后编译所有数据,而不会在每次传递时都覆盖变量,就像我当前的代码一样。

感谢您的帮助。

【问题讨论】:

  • 与其拥有一系列变量make1make2make3,不如考虑创建一个包含多个值的列表变量makes
  • 一个列表的列表怎么样,其中每个元素都是一个 [品牌、型号、年份] 的列表?

标签: python python-2.7


【解决方案1】:

为什么不在列表中累积一组值?这类似于建立一个结果表,表中的每一行对应你的元组。

试试这个:

results = []

while True:
    answer=raw_input('Is there another car? Y/N')
    if answer == 'Y':
        make = raw_input('Car manufacturer?')
        model = raw_input('Car Model?')
        year = raw_input('Year?')
        results.append((make, model, year))
    elif answer == 'N':
        break
    else:
        print 'Incorrect Response'
for result in results:
    print result

然后你会打印

(make1, model1, year1)
(make2, model2, year2)
... and so on

你可以通过命名元组变得更有趣:

import collections
Car = collections.namedtuple('Car', 'make model year')

results = []

while True:
    answer=raw_input('Is there another car? Y/N')
    if answer == 'Y':
        make = raw_input('Car manufacturer?')
        model = raw_input('Car Model?')
        year = raw_input('Year?')
        results.append(Car(make, model, year))
    elif answer == 'N':
        break
    else:
        print 'Incorrect Response'
for car in results:
    print car.make, car.model, car.year

命名元组是具有像对象一样的命名空间的元组,但不会占用 Python 进程的内存。一个完整的对象将属性存储在一个字典中,这会占用更多的内存。

【讨论】:

  • if answer=Y 应该是if answer=='Y'answer=N 也一样。不要忘记'Y''N' 是字符串,否则它们没有在你的代码中定义。
【解决方案2】:

使用您可以考虑命名为 Car 的类:

class Car:
     pass

然后,你可以实例化一个空的汽车列表,

cars = []

并且,在 while 循环期间,初始化一辆新车并将其附加到您的列表中:

car = Car()   
car.make=raw_input('Car manufacturer?')
car.model=raw_input('Car Model?')
car.year=raw_input('Year?')
cars.append(car)

类代表持久对象。列表中的所有元素都保持“活动”状态,您可以在用户输入完成后总结输入或任何您想做的事情。阅读有关listsclasses 的python 2.7 手册以了解更多信息。

【讨论】:

  • 感谢您的建议!没想到这么快就收到回复了。非常感谢。
  • 具有属性的对象列表权重较大,这对学习有好处,但我不会将其投入生产。
  • 是的,我看到了你关于命名元组的帖子,到目前为止我还不知道。然而,考虑到有问题的应用程序,我想 a) 指出 基本 概念,并且 b) 不要认为这里的内存会成为问题 :)
猜你喜欢
  • 2014-10-03
  • 1970-01-01
  • 1970-01-01
  • 2015-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-04
相关资源
最近更新 更多