[英]Possible to modify every first tuple element in a list of tuples?
我需要您的幫助,我有這樣的結構:
myList = [(1,2,3),(2,4,4),(1,5,6)]
這是一個元組列表。 現在,我需要獲取列表中每個元組的每個第一個元素,例如將每個1
替換為3
。
輸出應為: myList = [(3,2,3),(2,4,4),(3,5,6)]
我知道我可以做到:
for item in myList:
if item[0] == 1:
item[0] = 3
但是還有其他方法嗎? 是否無需遍歷整個列表?
類似於: myList.getFirstItemOfEachTuple.replace(1,3)
編輯:如有必要,我可以將myList
更改為[[1,2,3,4,5,6]...]
。
>>> myList = [(1,2,3,4,5,6),(4,5,6,7,8)]
>>> dic = {1:3}
>>> [ (dic.get(x[0],x[0]),) + x[1:] for x in myList]
[(3, 2, 3, 4, 5, 6), (4, 5, 6, 7, 8)]
如果myList
是列表列表:
>>> myList = [[1,2,3,4,5,6],[4,5,6,7,8]]
>>> [ [dic.get(x[0],x[0]) ] + x[1:] for x in myList]
[[3, 2, 3, 4, 5, 6], [4, 5, 6, 7, 8]]
修改原始列表:
>>> myList[:] = [(dic.get(x[0],x[0]),) + x[1:] for x in myList]
>>> myList
[(3, 2, 3, 4, 5, 6), (4, 5, 6, 7, 8)]
但是還有其他方法嗎? 無需遍歷整個列表?
不。並非沒有遍歷整個列表。
由於您希望檢查每個元組以查看要更改的元素是否為某個數字,因此您必須以某種方式遍歷整個列表。 因此,唯一剩下的考慮就是如何做到這一點。
存在着良好的,經過時間考驗和行業標准的指導方針,幫助決定如何編寫代碼:編寫代碼時,你應該有代碼的可讀性作為第一優先。 代碼效率遠不及第二。 此規則有一些例外,但此處與它們無關。
查看原始代碼。 它假定item
是一個list
,所以我也將:
for item in myList:
if item[0] == 1:
item[0] = 3
現在與Ashwini的建議進行比較:
dic = {1: 3}
myList[:] = [[dic.get(x[0], x[0])] + x[1:] for x in myList]
現在問問自己:
讓我們看一下效率:
您的原始代碼:對myList
每個項目,執行一次列表查找,然后可能執行一次列表分配,這都是非常快速的操作。
Ashwinis代碼:重建整個結構。 對於myList
每個項目,python需要創建三個新列表(如果要更改不是第一個項目則為五個 )。 Python必須為每個列表分配新的內存,並且垃圾回收大量的舊列表,這兩個操作都很慢。 所有這些都是為了使它擠成一線。
請使用原始代碼。 原因如下:
這意味着這是正確的方法。
如果您想要單線,請使其功能:
def conditional_sublist_assign(myList, index, from, to):
"""
For each `item` in `myList`, set `item[index] = to` if `item[index] == from`.
"""
for item in myList:
if item[index] == from:
item[index] = to
# Here's your one-liner:
conditional_sublist_assign(myList, 0, 1, 3)
為了使我的論點更有分量,以下是The Zen of Python中的一些相關文章:
具有列表理解能力。
條件第一個元組項必須為1:
>>> L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [[3] + x[1:] if x[0] == 1 else x for x in L]
[[3, 2, 3], [4, 5, 6], [7, 8, 9]]
元組而不是列表中列表的解決方案:
>>> L = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
>>> [(3,) + x[1:] if x[0] == 1 else x for x in L]
[(3, 2, 3), (4, 5, 6), (7, 8, 9)]
您可以在numpy中做到這一點,numpy也比python快50倍,因此,如果速度很重要,那絕對是可行的方法:
import numpy as np
myList = [(1,2,3),(2,4,4),(1,5,6)]
# convert list of tuples to 2D numpy array
myList = np.array(myList)
# get an array of all first element, syntax: myList[x, y] x and w and be ranges 1:3 og numbers like 1
# all the first elements are as follows:
first = myList[:,0]
# you can then make a true / false vector as follows
myList[first == 1,0] = 3
print myList
# prints:
#[[3 2 3]
# [2 4 4]
# [3 5 6]]
您不能更改元組的值,它是不可變的。 但是您將元組轉換為列表並更改值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.