N
N
nihi1ist2021-12-28 06:23:06
Python
nihi1ist, 2021-12-28 06:23:06

How to move zero values ​​to the end of the list?

There is a list with numbers, among the elements of the list there are zeros. Tell me how to move null values ​​to the end of the same list or a new one using list comprehension and/or slices?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vindicar, 2021-12-28
@nihi1ist

original_list = [0,1,8,3,0,4,5,0,0] #исходный список
new_list = [x for x in original_list if x != 0] #только ненулевые элементы
how_many_zeros =  len(original_list) - len(new_list) #сколько нулей потеряли?
new_list.extend( [0] * how_many_zeros ) # добавляем нужное количество нулей в конец

_
_ _, 2015-08-29
@AMar4enko

Che-t you have some gaps with relational algebra.
LEFT JOIN staff-city to staff gives N * M worst-case entries, where N is the number of entries in staff, M is the number of entries in staff-cities, and all entries in staff-cities are related to all entries in staff.
Then you programmatically collapse these entries into N, manually assembling the staff-cities into an array for each staff.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question