我刚刚编写了一些代码来将一个点列表转换为一个to / from元组的列表,但它感觉效率不高。
我想知道是否有人有任何建议让这更简洁?
from_point, to_point = None, None
point_list = []
for p in [1, 5, 2, 4, 7, 9]:
to_point = p
if from_point and to_point:
point_list.append((from_point, to_point))
from_point = to_point
print(point_list)
输入:[1, 5, 2, 4, 7, 9]
输出:[(1, 5), (5, 2), (2, 4), (4, 7), (7, 9)]
编辑:将点更改为非连续点。
答案 0 :(得分:2)
您始终可以使用zip
:
>>> p = [1, 5, 2, 4, 7, 9]
>>> point_list = list(zip(p[:-1], p[1:]))
>>> print(point_list)
[(1, 5), (5, 2), (2, 4), (4, 7), (7, 9)]
答案 1 :(得分:0)
另一种单行解决方案
input = [1, 2, 3, 4, 5, 6]
output = [(input[index], input[index+1]) for index in range(len(list)-1)]
print(output)
答案 2 :(得分:0)
这个怎么样?
x=[1, 5, 2, 4, 7, 9]
print [ tuple(x[i:i+2]) for i in xrange(len(x)-1) ]
答案 3 :(得分:0)
from yahoo_finance import Share
with open('positions.txt', 'r') as fp:
result = fp.readlines()
for ticker in result:
#the yahoo finance functions are below
var2 = Share(ticker)
print(var2.get_price())