2017-06-20 90 views
-1

我还是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) 
+0

告诉你整个代码。您可能忘记访问正确的变量 – CIsForCookies

+4

您的意思是保时捷?另外,什么是'名称'? –

+2

对不起,但你的代码是没有用的。有两个变量没有任何来源,它不清楚你的评论意味着什么。 –

回答

0
# 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) 
+0

它为我工作,非常感谢你。 –

0

为什么你没有直接使用车辆列表循环哥哥,例如:

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

我希望它能帮助:)

0
#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. 
0
vehicles = ["Honda", "Porche", "Cadilac", "Toyota"] 
number = 0 
for vehicle in vehicles: 
    number += 1 
    print(str(number) + ". " + vehicle) 

我希望这是你的意思。