重复的结果总是阴郁的

2024-10-03 15:23:37 发布

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

我对python还是个新手。我尝试使用循环时遇到问题。我有两个变量,第二个变量总是给我相同的结果。在我的示例中,我有这样一个数据库:

id | name
1    porce
2    cadilcac
3    honda
4    toyota

首先,我尝试在id上循环,它工作得很好。但是当我尝试循环name时,结果总是错误的,如下所示:

1.porce
2.porce
3.porce
4.porce

我想要的结果是:

1.porce
2.cadilcac
3.honda
4.toyota

这是我的密码:

number = 0
for id_id in id_number:
    dd = name # here i call the name by id
    number += 1
    print(number)
    print(dd)

Tags: nameid数据库密码示例numberfor错误
3条回答

为什么不直接使用车辆列表进行循环兄弟,例如:

vehicles = ["Honda", "Porche", "Cadilcac", "Toyota"]
number = 0
for vehicle in vehicles:
    number += 1
    print(number)
    print(vehicle)

希望有帮助:)

#set counter
count = 1

#set list
my_list = ['porce', 'cadilac', 'honda', 'toyota']

#loop through the values and use the counter to assign to the first part of
# your print statement
for item in my_list:

    # this format would be the same as the one that you requested
    print('{}.{}'.format(count,item))
    # increment the counter
    count += 1

However, if you directly import from a database, a set of tuples would be a better structure than that of a list. Otherwise, it would be better to employ a dictionary type structure.
# using list
    vehicles = ["Honda", "Porche", "Cadilcac", "Toyota"] 
    number = 0
    for vehicle in vehicles:
        number += 1
        print(number),  # ',' is used to print both columns in a single line
        print(vehicle)

    # using dictionary

    vehicles = {1: 'porce',2:'cardilac',3:'honda',4:'toyota'}
    number=0
    for id_id in dict:
            dd= dict[id_id] 
            number += 1
            print(number),
            print(dd)

相关问题 更多 >