Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
59 views
in Technique[技术] by (71.8m points)

python - Getting a list (and not a list of lists) within a code

I would need to transform a list of lists into a simple list. Currently I have (wrong output):

Col          List1
mouse   ([[dog, horse, cat]])
horse   ([[mouse, elephant]])   
tiger   ([[]],[[]])  

I would like to have

Col          List1
mouse   [dog, horse, cat]   
horse   [mouse, elephant]   
tiger   []  

Code to create the first list above (and that needs to be updated accordingly in order to fix the issue) is

def alexa(x):
        surnames, score_lists = [],[]

   ...
      
        surnames.append(my_surname)
        score_lists.append(scores)
        return surnames, score_lists

surnames, score_lists = my_function(df)

df['Surname'] = df.Name.apply(lambda x: my_function(x))
df['Score'] = df.Name.apply(lambda x: my_function(x))

(more information in this post: How to avoid code repetition and redundancy)

I have tried as follows:

import itertools

list_surnames=list(itertools.chain(* surnames))
list_scores=list(itertools.chain(* score_lists))

However it seems to be wrong. If you have any idea on how I can ge the expected output above, it would be great.

question from:https://stackoverflow.com/questions/65877972/getting-a-list-and-not-a-list-of-lists-within-a-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use numpy.ravel:

import numpy as np

df["List1"] = df["List1"].apply(np.ravel)
#     Col              List1
#0  mouse  [dog, horse, cat]
#1  horse  [mouse, elephant]
#2  tiger                 []

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...