例如我有一个这样的列表:
list = [3, 4, "-", 7, "+", 9, "/", 2]
在我的上下文中,这是一个计算器的输入,每个数字作为一个列表项到达,但例如"3", "4"
应该是"34"
。我最终得到了这段代码:=
for index, item in enumerate(list):
a = index + 1
if type(item) is int and type(list[a]) is int:
list[index] = int(str(item) + str(list[a]))
list.pop(a)
行list.pop(a)
不起作用,因为对于最后一项,您无法检查下一项是否为int,因为下一项不存在,它超出了范围。你有什么办法不让这种事发生吗?
有两种方法:
def digits_to_num(digits):
return sum(n*10**i for i, n in enumerate(reversed(digits)))
def _combine_ints(arr):
digits = []
for item in arr:
if isinstance(item, int):
digits.append(item)
else:
if digits:
yield digits_to_num(digits)
digits = []
yield item
if digits:
yield digits_to_num(digits)
def combine_ints(arr):
return list(_combine_ints(arr))
或
import re
def combine_ints(arr):
chunked = re.findall(r'd+|[+/*-]', ''.join(map(str, arr))
return [int(i) if i.isdecimal() else i for i in chunked]
answer = combine_ints([1, 2, 3, 4, '+', 5, 6]) # -> [1234, '+', 56]
如果你需要处理浮点数,这些需要调整。
您可以简单地在if
语句中添加另一个条件:
for index, item in enumerate(list):
a = index + 1
if a < len(list) and type(item) is int and type(list[a]) is int :
list[index] = int(str(item) + str(list[a]))
list.pop(a)
new_list=[]
lis = [3, 4, "-", 7,8,9,10, "+", 9, "/", 2,3]
tmp=''
for i in lis:
if str(i).isdigit(): #checking whether "i" is a digit or not
tmp+=str(i) # If the next value is also a digit, we are combining them and storing them in a "tmp."
else:
new_list.append(int(tmp)) # If "i" is not a digit, append the stored "tmp" into new_list.
new_list.append(i)
tmp=''
print(new_list+[int(tmp)])
希望这对你有帮助!