[英]How can I convert a float list into an int list of pairs in Python?
任務是將[1.5, 1.2, 2.4, 2.6, 3.0, 3.3]
轉換為[(2, 1), (2, 3), (3, 3)]
目前,我使用蠻力方式來做到這一點:
result = []
for i in range(0, len(nums), 2):
x = int(round(nums[i]))
y = int(round(nums[i + 1]))
result.append((x,y))
return result
是否有更簡潔的內置解決方案(例如,使用itertoools
)?
您可以將它們zip
在一起(使用[::2]
和[1::2]
交替的模式),然后隨身攜帶:
L = [1.5, 1.2, 2.4, 2.6, 3.0, 3.3]
L = [(round(x), round(y)) for x, y in zip(L[::2], L[1::2])]
# [(2, 1), (2, 3), (3, 3)]
您可以將iter()
與zip()
來創建對。 之后,您可以舍入值。
我將使用@Alex答案中的代碼來顯示差異
L = [1.5, 1.2, 2.4, 2.6, 3.0, 3.3]
it = iter(L)
L = [(round(x), round(y)) for x, y in zip(it, it)]
假定給定列表始終由偶數個元素組成:
l = [1.5, 1.2, 2.4, 2.6, 3.0, 3.3]
def f(s):
for i in range(int(len(s)/2)):
yield (round(s[2*i]), round(s[2*i+1]))
print(list(f(l)))
#[(2, 1), (2, 3), (3, 3)]
我有一個使用zip的解決方案。 您也可以嘗試。
l = [1.1,2.2,3.3,4.4,5.5,6.6]
def fun(l):
x = list(zip(*[l[i::2] for i in range(2)]))
print(x)
ll = round[(x) for x in l]
fun(ll)
#[(1, 2), (3, 4), (6, 7)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.