'Filter index total from a list by passing the total value as a function argument
If I know perfectly how many indexes I'm looking for, I do it like this:
def main():
lst = [['111','222','333'],['111','222','3333'],['111','222','333']]
new_sublist = [[sublist[0],sublist[1]] for sublist in lst]
print(new_sublist)
if __name__ == '__main__':
main()
Result:
[['111', '222'], ['111', '222'], ['111', '222']]
Now I'm wanting to do the same thing but putting the amount of index as a function argument:
def main(total_index):
lst = [['111','222','333'],['111','222','3333'],['111','222','333']]
indexis = [f'sublist[{i}]' for i in range(total_index)]
new_sublist = [eval(','.join(indexis)) for sublist in lst]
print(new_sublist)
if __name__ == '__main__':
main(2)
Result:
[('111', '222'), ('111', '222'), ('111', '222')]
But using loop and eval seems to me to be a very archaic way of dealing with this, is there a correct method to do this same work?
Solution 1:[1]
You can just slice your list with [:len] notation
def main(total_index):
lst = [['111','222','333'],['111','222','3333'],['111','222','333']]
new_sublist = [sublist[:total_index] for sublist in lst]
print(new_sublist)
if __name__ == '__main__':
main(2)
Solution 2:[2]
The slice method in @lejlot's answer is best, but if you want to see how to do it with a list comprehension without eval(), you can use a nested list comprehension:
def main(total_index):
lst = [['111','222','333'],['111','222','3333'],['111','222','333']]
new_sublist = [[sublist[i] for i in range(total_index)] for sublist in lst]
print(new_sublist)
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 | lejlot |
| Solution 2 | Barmar |
