python - 在循环中更改/添加变量。 (Python 2.7)

标签 python python-2.7

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

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

这就是我所拥有的:

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 等)。这样我就可以在之后编译所有数据,而不会在每次传递时覆盖变量,就像我当前的代码一样。

感谢您的帮助。

最佳答案

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

试试这个:

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 进程的内存。完整对象将属性存储在字典中,这会占用更多内存。

关于python - 在循环中更改/添加变量。 (Python 2.7),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24251936/

相关文章:

python - 将字符串中的每个字符更改为字母表中的下一个字符

Python 元组与生成器

Python:如何让不同版本的 python 访问相同的模块?

python - 在 Python 中创建一个新文件,其中包含两个数据帧上的常见匹配项

python - 在 Sqlalchemy 中更新多列

python - 如何在 Python 模块中正确使用相对或绝对导入?

python - 如何在Django的views.py中管理slug

ios - lldb python basic - 在函数断点内打印全局数组的值

python - 填补多个用户缺失的时间段

python - 在 QTableView 单元格中绘制可调整的文本