【问题标题】:How to implement for loop using python?如何使用python实现for循环?
【发布时间】:2020-02-04 04:05:58
【问题描述】:

这段代码做了一个小迭代,并给出如下输出

代码:

result = []
start = 1000
lst = ['20','30','50','1','200']
for i in lst:
    data = {
           "total_members_present":start,    
           "count": i,
           "total_members_now":start - int(i)
           "id":'12345'
          }
    start = data["total_members_now"]
    result.append(data)

print(result)

输出:

[{'count': '20', 'total_members_now': 980, 'total_members_present': 1000,'id':'123456'},
 {'count': '30', 'total_members_now': 950, 'total_members_present': 980,'id':'123456'},
 {'count': '50', 'total_members_now': 900, 'total_members_present': 950,'id':'123456'},
 {'count': '1', 'total_members_now': 899, 'total_members_present': 900,'id':'123456'},
 {'count': '200', 'total_members_now': 699, 'total_members_present': 899,'id':'123456'}]

需要使用for循环并添加id列表

示例:id =['12345','789456']

需要在for循环中使用id:

试过这个:

 id =['12345','789456']
result = []
start = 1000
lst = ['20','30','50','1','200']

for ids  in id :

    for i in lst:
        data = {
               "total_members_present":start,    
               "count": i,
               "total_members_now":start - int(i)
               "id":ids
              }
        start = data["total_members_now"]

result.append(data)

需要的输出:

对于每个id start = 1000 应该重置为 1000 并且应该从头开始,这里循环开始了。对于 id 789456,start 应该是 1000,但这里是 899。

【问题讨论】:

    标签: python python-3.x loops for-loop iteration


    【解决方案1】:
    id =['12345','789456']
    result = []
    lst = ['20','30','50','1','200']
    
    for ids  in id :
        start = 1000
        for i in lst:
            data = {
                   "total_members_present":start,    
                   "count": i,
                   "total_members_now":start - int(i)
                   "id":ids
                  }
            start = data["total_members_now"]
            result.append(data)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-15
      • 2013-04-20
      相关资源
      最近更新 更多