我有一个有趣的问题要解决。在迭代过程中,如何更改迭代方向(反向)?让我解释。我有这样的清单:
a = ['one', 'two', 'three', 'four']
并说,如果第四个元素包含字母“ r”,则返回上一步 并添加到该数字3之前的元素,直到元素的长度小于或等于10。类似这样的东西:
for index, element in enumerate(a):
if 'r' in element and len(a[index-1]) <= 10:
# go back solution comes here
a[index-1] += '3'
else:
continue
很明显,我不能只坚持使用a[index-1] += '3'
。因为那不会跟踪迭代的位置,对。因为程序需要知道需要返回多少次并扩展元素。
有Pythonic解决方案吗?我知道range(10, 0, -1)
和reverse(<iterator>)
,但这在这种情况下无济于事。
答案 0 :(得分:2)
我想Sid的回答解决了这个问题。我只是想指出,while
循环并不是真正必要的。在Python中,您可以乘以字符串:3*"hi "
将返回hi hi hi
,并且每个元素的最终长度都是已知的(10)。下面是一个整洁/丑陋的(取决于您问谁):产生与Sid解决方案相同结果的衬管。
a = ['one', 'two', 'three', 'four']
char = "3" # char to add to chosen elements in list
length = 10 # the final char-length after adding the chars to list elements
trigger = "r" # char to trigger the adding of new chars.
b = [x if (i==len(a)-1 or trigger not in a[i+1]) else x+(char*(length-len(x))) for i, x in enumerate(a)]
print(b) # ['one', 'two3333333', 'three33333', 'four']
答案 1 :(得分:1)
也许这就是您想要的:
a = ['one', 'two', 'three', 'four']
count = 0
while count < len(a):
element = a[count]
#print('in loop')
if 'r' in element and count > -1 and len(a[count-1]) <= 10:
# go back solution comes here
#print('going back')
a[count-1] += '3'
count -= 1
#print('done')
print(a)
else:
#print('not found')
count += 1
continue
输出:
['one', 'two3', 'three', 'four']
['one', 'two33', 'three', 'four']
['one', 'two333', 'three', 'four']
['one', 'two3333', 'three', 'four']
['one', 'two33333', 'three', 'four']
['one', 'two333333', 'three', 'four']
['one', 'two3333333', 'three', 'four']
['one', 'two33333333', 'three', 'four']
['one', 'two33333333', 'three3', 'four']
['one', 'two33333333', 'three33', 'four']
['one', 'two33333333', 'three333', 'four']
['one', 'two33333333', 'three3333', 'four']
['one', 'two33333333', 'three33333', 'four']
['one', 'two33333333', 'three333333', 'four']
答案 2 :(得分:0)
for index, element in enumerate(a):
if 'r' in element and len(a[index-1]) <= 10:
while len(a[index-1]) <= 10:
a[index-1] += '3'
else:
continue
也许这不是最Python的方式,但是我确实觉得它很优雅。取决于您问谁。