我有以下代码片段,我想以这样的方式更改它,我想为每个changeInfo ['changeInfo'] [1..x]进行循环,我该怎么做
for changeInfo in MainchangeInfo:
if (changeInfo['CRStatus'] == 'Fix' and (('Not Provided' in changeInfo['changeInfo'][0]['Url'] or 'Wrong change Provided' in changeInfo['changeInfo'][0]['Url']) or 'NEW' in changeInfo['changeInfo'][0]['Status'] or 'ABANDONED' in changeInfo['changeInfo'][0]['Status'] or 'Yes' not in changeInfo['RNotesStatus'] or 'Provided' not in changeInfo['RCAInfo'] or 'False' in str(changeInfo['IsDevComplete']))):
if 'Wrong change Provided' in changeInfo['changeInfo'][0]['Url'] or changeInfo['changeInfo'][0]['Info'] != 'Available' ://want to loop over for changeInfo['changeInfo'][0]
changeMailBody = changeMailBody + "<tr bgcolor=\"Red\">"
答案 0 :(得分:0)
[1..x]
是什么意思?
如果要循环遍历changeInfo['changeInfo']
中的“前x个”元素(在这种情况下,您的意思是[0..x]
?),您可以使用切片表示法:
for item in changeInfo['changeInfo'][:x]:
# do stuff
如果你真的想从1到x,即跳过你可以做的第一个元素:
for item in changeInfo['changeInfo'][1:x]:
# do stuff
请参阅此处的文档:
http://docs.python.org/2.3/whatsnew/section-slices.html
编辑:
在评论中澄清之后,您甚至不需要切片表示法,只需要for item in changeInfo['changeInfo']
...我认为您的完整示例如下:
for changeInfo in MainchangeInfo:
for item in changeInfo['changeInfo']:
if (changeInfo['CRStatus'] == 'Fix' and (('Not Provided' in item['Url'] or 'Wrong change Provided' in item['Url']) or 'NEW' in item['Status'] or 'ABANDONED' in item['Status'] or 'Yes' not in changeInfo['RNotesStatus'] or 'Provided' not in changeInfo['RCAInfo'] or 'False' in str(changeInfo['IsDevComplete']))):
if 'Wrong change Provided' in item['Url'] or item['Info'] != 'Available' ://want to loop over for changeInfo['changeInfo'][0]
changeMailBody = changeMailBody + "<tr bgcolor=\"Red\">"
答案 1 :(得分:0)
您可以使用显式循环执行此操作:
for change in changeInfo['changeInfo']:
info = change['info']
# do stuff with it
或者,如果你想把它写成一个理解:
infos = [change['info'] for change in changeInfo['changeInfo']]
或者,如果你只想要一个迭代器,而不是一个列表:
infos = (change['info'] for change in changeInfo['changeInfo'])
在任何情况下,您都会获得changeInfo['changeInfo'][0]['info']
,然后是changeInfo['changeInfo'][1]['info']
,依此类推。
我在这里假设changeInfo['changeInfo']
是一个列表,而不是一个dict,它的键恰好是小整数。如果该假设有误,请在您选择的任何解决方案中将changeInfo['changeInfo']
替换为changeInfo['changeInfo'].values()
。 (当然,在这种情况下,订单将是任意的,但这正是您对dict
的期望。)
因此,在您现有的代码中,而不是:
if ('Wrong change Provided' in changeInfo['changeInfo'][0]['Url'] or
changeInfo['changeInfo'][0]['Info'] != 'Available'):
...我将使用生成器表达式和any
函数,如下所示:
if any('Wrong change Provided' in change['Url'] or change['Info'] != 'Available'
for change in changeInfo['changeInfo']):
现在,不是检查changeInfo['changeInfo']
中的第一个值是否为真,即changeInfo['changeInfo'][0]
- 您正在测试是否属实changeInfo['changeInfo']
中任何的值。据我所知,这正是你想要的。