'Is there a more Pythonic way to write this? Filling multiple lists to desired length
I'm struggling with making my lists of strings a DataFrame because they are different sizes.
So, I'm running code to get the length of the largest list and then adding 'Null' to the other lists until they are all the same size.
Problem is I have 7 lists and need to repeat the below code for all of them and it feels terribly redundant/repetitive. Any ideas to revise?
# 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
Output newlist4 = List filled to desired length (lenMax) with original values + 'Null' as repeating value.
Any ideas or advice here?
Please see response of @Freddy Mcloughlan for answer.
Solution 1:[1]
You can just use extend
to add on None
values for the lists:
Example values:
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]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |