简体   繁体   English

python,在嵌套的for循环中遍历列表

[英]python, iterate through a list in a nested for loop

Im trying to generate from random variables for an inserting in a database but I'm always getting the same string when i try to iterate thru the widgetname list. 我试图从随机变量中生成一个插入数据库,但是当我尝试通过widgetname列表进行迭代时,我总是得到相同的字符串。 I'm getting gadget all the 5 iterations. 我将获得所有5个迭代的小工具。 How do i get different string? 我如何获得不同的字符串?

output Im getting 输出即时消息

wd name: gadget
91
9
wd name: gadget
87
1
wd name: gadget
41
10
wd name: gadget
16
10
wd name: gadget
50
4 

my code: 我的代码:

widgetname=['sprocket', 'gizmo', 'gadget']
price=0
design_date='2010-02-10'
version=0
design_comment='design comment goes here'

count = 0
while (count < 5):
    count += 1
    for widget in widgetname:
        widget_name = widget
    for i in range(count):
        price=random.randint(1.0, 100.0)
    for j in range(count):
        version=random.randint(1.0, 10.0)

    print('wd name: '+widget_name)
    print(price)
    print(version)

You don't need all the loops, just the outer one, see the snippet below 您不需要所有循环,只需要外部循环,请参见下面的代码段

for count in range(5):
    widget_name = random.choice(widgetname)   
    price=random.randint(1, 100)
    version=random.randint(1, 10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM