如何在Python中循环使用字符串格式?

时间:2015-06-15 01:00:28

标签: python list

我有两个变量,我正在构建一个新的字符串,但其中一个变量没有正确循环。我期待几个值,但结果输出是序列中的第一个值。如何正确构造/放置字符串格式,以便正确地正确遍历任一变量?如果我将字符串格式化为循环,则它会正确循环,即如果它在计数中,则计数会正确显示,但项目不会。

代码:

for dSr in lServiceRequests:
            dListOfLa311ElectronicWaste = dSr["ListOfLa311ElectronicWaste"]
            if("La311ElectronicWaste" in dListOfLa311ElectronicWaste):
                lLa311ElectronicWaste = dListOfLa311ElectronicWaste["La311ElectronicWaste"]
                for dla311ElectronicWaste in lLa311ElectronicWaste:
                    v_ewaste_item_count= dla311ElectronicWaste[K_ewaste_Item_Count]
                    print v_ewaste_item_count

输出:

1
1
1
2
Computers
Laptops/Tablets
Cell Phone
TV (Any Size)
1
1
1
2
Computers
Laptops/Tablets
Cell Phone
TV (Any Size)
1
1
1
2
Computers
Laptops/Tablets
Cell Phone
TV (Any Size)
1
1
1
2
Computers
Laptops/Tablets
Cell Phone
TV (Any Size)
1
1
1
2
Computers
Laptops/Tablets
Cell Phone
TV (Any Size)
1
1
1
2
Computers
Laptops/Tablets
Cell Phone
TV (Any Size)
1
1
1
2
Computers
Laptops/Tablets
Cell Phone
TV (Any Size)
1
1
1
2
Computers
Laptops/Tablets
Cell Phone
TV (Any Size)
1
1
1
2
Computers
Laptops/Tablets
Cell Phone
TV (Any Size)

具有列表理解的代码:

  for dSr in lServiceRequests:
            k_ewaste_info = ' '
            dListOfLa311ElectronicWaste = dSr["ListOfLa311ElectronicWaste"]
            if("La311ElectronicWaste" in dListOfLa311ElectronicWaste):
                lLa311ElectronicWaste = dListOfLa311ElectronicWaste["La311ElectronicWaste"]
                for dla311ElectronicWaste in lLa311ElectronicWaste:
                    v_ewaste_type = dla311ElectronicWaste[K_ewaste_type]
                    # print v_ewaste_type
                    v_ewaste_item_info = '{0},  {1} '.format(v_ewaste_item_count, v_ewaste_type)
                    if k_ewaste_info != v_ewaste_item_info:
                        k_ewaste_info = v_ewaste_item_info
                        print v_ewaste_item_info

列表理解的输出:

2,  Computers 
2,  Laptops/Tablets 
2,  Cell Phone 
2,  TV (Any Size) 
2,  Computers 
2,  Laptops/Tablets 
2,  Cell Phone 
2,  TV (Any Size) 
2,  Computers 
2,  Laptops/Tablets 
2,  Cell Phone 
2,  TV (Any Size) 
2,  Computers 
2,  Laptops/Tablets 
2,  Cell Phone 
2,  TV (Any Size) 
2,  Computers 
2,  Laptops/Tablets 
2,  Cell Phone 
2,  TV (Any Size) 
2,  Computers 
2,  Laptops/Tablets 
2,  Cell Phone 
2,  TV (Any Size) 
2,  Computers 
2,  Laptops/Tablets 
2,  Cell Phone 
2,  TV (Any Size) 
2,  Computers 
2,  Laptops/Tablets 
2,  Cell Phone 
2,  TV (Any Size) 
2,  Computers 
2,  Laptops/Tablets 
2,  Cell Phone 
2,  TV (Any Size) 

0 个答案:

没有答案