![](/img/trans.png)
[英]Single list rotation of the first half with the other half, including odd number of elements
[英]Combine n elements in first half of list with elements in other half of a list, if number of elements in a list is greater than 2
我在處理列表中的元素時遇到問題。 准確地說是在列表列表中。 例如,我有從文件中讀取的元素列表:
list_1 = [['void', None], ['uint8', 'f_MbistTestType_u8'], ['uint8', 'uint32', 'f_MbistTestType_u8', 'f_chip_id_u32'], ['void', None], ['void', None], ['void', None], ['void', None]]
在這種情況下,第三個元素有兩個以上的元素。 我想用元素 3 切換元素 2。所以它看起來像這樣:
list_1[2] = ['uint8', 'f_MbistTestType_u8', 'uint32', 'f_chip_id_u32']
如果有 6 個元素,即
list_example = ['uint8', 'uint32', 'void', 'f_chip_id_u32', 'f_MbistTestType_u8', None]
操作后應該是這樣的:
list_example_sorted = ['uint8', 'f_chip_id_u32', 'uint32', 'f_MbistTestType_u8', 'void', None]
現在我知道如何獲取這些元素,以防我只出現一次超過 2 個元素,但不知道如何切換它們的位置,也不知道如果出現不止一次該怎么做:
for elements in list_1:
print(elements)
if len(elements) > 2:
list_el = elements
print(list_el)
我試圖彈出它們和 append,但它不能很好地擴展超過 4 個元素。
我試過用swap function,但是好像不行還是我用錯了?
通過輸入[1, 1, 1, 2, 2, 2]
和所需的 output [1, 2, 1, 2, 1, 2]
,即您想要左半部分的第一個元素,然后是第一個右半部分的元素等等。 為了使它更明顯:
input = [1, 2, 3, 4, 5, 6]
output = [1, 4, 2, 5, 3, 6]
定義一個 function combine_inplace
,它將左半部分的第 i 個元素與l
右半部分的第 i 個元素組合在一起:
def combine_inplace(l):
mid = len(l) // 2
ptr = 0
for left, right in zip(l[:mid], l[mid:]):
l[ptr], l[ptr+1] = left, right
# Increment pointer ptr by 2 for the next combination
ptr += 2
combine_inplace
改變傳遞的列表l
zip
遍歷兩個列表ptr
遞增 2 以獲得l
的下一個列表索引如果您不想改變列表本身,您可以創建一個由 function combine
返回的新combined
列表:
def combine(l):
mid = len(l) // 2
combined = []
for left, right in zip(l[:mid], l[mid:]):
combined.extend((left, right))
return combined
l
combined
的空列表以存儲組合值zip
遍歷列表的兩半combined
列表這使用與combine_inplace
相同的邏輯,但您保持原始列表不變。
這兩個函數都將給定列表的左半部分和右半部分的元素組合在一起。 唯一的區別是使用combine
你必須將返回的列表存儲在一個變量中才能訪問它。
>> l = [1, 1, 1, 2, 2, 2]
>> combine_inplace(l)
>> print(l)
[1, 2, 1, 2, 1, 2]
>> input_list = [1, 2, 3, 4, 5, 6]
>> output_list = combine(input_list)
>> print(output_list)
[1, 4, 2, 5, 3, 6]
現在使用combine
或combine_inplace
將列表中length > 2
的元素組合到列表中:
ll = [[1, 2], [1, 2], [1, 1, 2, 2], [1, 2], [1, 2, 3, 4, 5, 6]]
# Non-destructive way using combine to create a new list comb_ll
comb_ll = []
for el in ll:
if len(el) > 2:
el = combine(el)
comb_ll.append(el)
# Mutates the original list
for i in range(len(ll)):
if len(ll[i]) > 2:
combine_inplace(ll[i])
在這兩種情況下,您都會得到相同的結果:
>> print(comb_ll)
[[1, 2], [1, 2], [1, 2, 1, 2], [1, 2], [1, 4, 2, 5, 3, 6]]
>> print(ll)
[[1, 2], [1, 2], [1, 2, 1, 2], [1, 2], [1, 4, 2, 5, 3, 6]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.