跳转到字符串中的下一个字符,而不在 Python 中使用该字符的索引



我需要使用字符而不是索引来遍历字符串。例如,对于字符串s。它将类似于:

for n in s:
.........
.........

其中CCD_ 2是字符串中的一个字符。有没有什么方法可以引用这个"for"循环中的下一个立即符(来自这个字符串(,而不使用它的索引?

上下文:这是针对LeetCode中将罗马数字转换为数字的问题,为此我编写了如下代码:

class Solution:
def romanToInt(self, s: str) -> int:
'''
Logic: 
1. Create two cases: non on right is lesser than no on left and vice versa 
2. If right > left, subtract left from right and add to value. Skip one position in loop. 
3. If left > right, simply add value of left to total, and move to next in loop.     

'''
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
val = 0 # value of roman numeral 

for n in s:
if roman[n] > roman[n+1]:
val += roman[n]
n = n + 1
return n 
elif roman[n] < roman[n+1]:
val += roman[n+1]-roman[n]
n = n + 2
return n 
return val 

这显然在每次我尝试将字符CCD_ 3添加到整数CCD_。这就是为什么我正在寻找一种迭代chracterwise的方法,而不是使用索引。

谢谢!

我认为你想要的东西没有任何意义。。。我能想到的最好的方法是这样的。。

for i, n in enumerate(s):
next_char = s[min((i+1, len(s)-1))]
# do your stuff

您可以创建一个字符偏移量为1的新字符串,将其与原始字符串压缩,然后迭代得到的元组列表。

for this_char, next_char in zip(s, list(a)[1:] + [None]):
# next_char will be None in the last iteration
pass

解释

# convert the string to a list
offset_string = list(a)
# shift the list by one via slicing
offset_string = offset_string[1:]
# since the list is 1 element shorter than the string, add a `None` to the end so we still can have the last character
offset_string = offset_string + [None]
for this_char, next_char in zip(s, offset_string):
pass

最新更新