Python数组转换为整数并加在一起?

时间:2015-11-05 04:07:38

标签: python list

我正在玩这个python代码。我只想知道如何将数组中表示的数字转换为整数,然后从另一个中减去1的值?

我使用的数组只是一个例子。

x = 0
results1 = ["8", "2", "3","1"]
while x != len(results1):
  firstthing1 = results1[x]
  x = x+1
  firstthing2 = results1[x]
  print(int(firstthing1) + int(firstthing2))

2 个答案:

答案 0 :(得分:0)

这样的东西?

results1 = ["8", "2", "3","1"]
print([ int(x) - int(y) for x,y in zip(results1, results1[1:]+[0])])

答案 1 :(得分:0)

以下示例将0替换为无法转换为int的值

from itertools import tee
results1 = ["8", "2", "foo", "3","1"]


def result_gen(seq):
    for item in seq:
        try:
            yield int(item)
        except ValueError:
            yield 0  # or pass if you want to ignore bad values


first, second = tee(result_gen(results1))
next(second)


for i, j in zip(first, second):
    print(i + j) # or print(i - j) or print (j - i) etc.