简体   繁体   中英

python3 - for/while loop through a list

is there an another way to implement the following idea:

I'm trying to form sublists (only of numbers) using the for loop. I want to iterate over the given list, starting as usual from the first element until a letter comes up. If some kind of character (or letter) appears, then the for loop should stop exactly at that position, return the so far formed list and continue working. At the end, the main list should contain all of the formed sublists and return them too.

I tried to use a while loop, since this kind of loop should jump over all elements of the list and check simultaneously if each element is an integer or not. But unfortunately my implementation didn't work. And by the way, I would rather an implementation without using the itertool (groupby).

I'd appreciate your help!

a_list = [1, 1, 'z', 1, 'x', 1, 1, 'c', 1, 1, 1, 'v', 1]

main_list = []
small_list = []

for i in a_list:
    if isinstance(i, int):
        small_list.append(i)
    else:
        main_list += [small_list]
        small_list = []
main_list += [small_list]
    

print("main_list: ", main_list)
# [[1, 1], [1], [1,1], [1,1,1], [1]]

final_list = []
for i in main_list:
    item_length = len(i)
    final_list += [item_length]
print("final list is: ", final_list)

如果数组中的所有项目都是单个字符而不是12AB类的东西,则可以join所有项目连接到一个string '11z1x11c111v1' ,然后使用 Python字符串方法,可能是find()和带有:子列表的组合。

import itertools
a_list = [1, 1, 'z', 1, 'x', 1, 1, 'c', 1, 1, 1, 'v', 1]
bool_list = [True if isinstance(e, int) else False for e in a_list]
group_list = [list(g) for _, g in itertools.groupby(enumerate(bool_list), key = lambda x: x[-1])]
final_list = [len(e) for e in group_list if e[-1][-1]]
print("final list is: ", final_list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM