[英]Is there a more Pythonic way to write this? Filling multiple lists to desired length
我正在努力使我的字符串列表成為 DataFrame,因為它們的大小不同。
所以,我正在運行代碼來獲取最大列表的長度,然后將“Null”添加到其他列表中,直到它們的大小都相同。
問題是我有 7 個列表,需要為所有列表重復以下代碼,感覺非常冗余/重復。 有什么想法可以修改嗎?
# Using entry 4 for the purpose of this example (this repeats for each lenX value)
# Getting lengths and max length
len4 = len(list4)
lenMax = max(len1, len2, len3, len4, len5, len6, len7)
# defining function to allow adding str to list as multiple elements
def createlist4 (size4, value4):
requiredlist4 = [value]*size
return requiredlist4
size4 = (lenMax - len4)
value4 = 'Null'
diff4 = createlist4(size4, value4)
newlist4 = list4 + diff4
輸出 newlist4 = 使用原始值填充到所需長度 (lenMax) 的列表 + 'Null' 作為重復值。
這里有什么想法或建議嗎?
請參閱@Freddy Mcloughlan 的回復以獲得答案。
您可以使用extend
為列表添加None
值:
示例值:
list1 = [1, 2]
list2 = [1, 2]
list3 = [1, 2, 3]
# Add all your lists into one large list
lists = [list1, list2, list3]
# This gets the longest length in lists
lenMax = max(len(x) for x in lists)
# This is the value you are extending by
value = None # Not 'null' (I'm assuming None is more suitable)
for i in range(len(lists)):
# For every list, extend it with values (len-max - len) times
lists[i].extend([value] * (lenMax - len(lists[i])))
>>> lists
[[1, 2, None],
[1, 2, None],
[1, 2, 3]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.