简体   繁体   中英

Convert nested for loop to list comprehension

I made for loop code like this:

all = []
for sen_list in sen_lists:
    te = []
    for ele in sen_list:
        boolean = ele == "."
        te.append(boolean)
    all.append(te)

sen_lists = [['a', 'b', 'c', 'd', '.', '.'], ['e', 'f', 'g', 'h']]

upper code works well... but I want to convert list comprehension code.

I try like this:

[ele == "." for sen_list in rawdf.TEXT[:10] for ele in sen_list]

but this code is doesn't work.

please let me know. thanks.

Consider a nested list comprehension. Or, in other words, a list comprehension of list comprehensions.

The inner one represents your inner for loop. The outer one represents your outer for loop.

sen_lists = [['a', 'b', 'c', 'd', '.', '.'], ['e', 'f', 'g', 'h']]

res = [[ele == "." for ele in sen_list] for sen_list in sen_lists]

# [[False, False, False, False, True, True], [False, False, False, False]]

You need to wrap you boolean logic in [ ] so that boolean = knows what it is supposed to equal.

boolean = [ele == '.']

I don't know the logic to do it all on one line, like you're trying to do at the end of your question.. would be cool though.

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