简体   繁体   中英

Nested Lists, Python from bash Output

How do we create a nested list by taking off the terminal output ?

Ex: I am querying the terminal to get some output (In this case, it's related to Yarn)

import subprocess    
outputstring=subprocess.check_output("yarn application -list | grep " + user, shell=True)    
mylist = (re.split("[\t\n]+",outputstring))=

This produces a output on each line for each Job that's running on Yarn. Eg:

line1 = a,b,c,d,e
line2 = f,g,h,i,j
line3 = k,l,m,m,o

I am able to create a list off this output, but as a single list with all the words as comma separated values like

mylist = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o] using the regex above.

but need to create a list as below:

mylist = [[a,b,c,d,e], [f,g,h,i,j], [k,l,m,n,o]] 

ie:

mylist = [[line1],[line2],[line3]]

can anyone please suggest how to achieve this ?

Regex I am currently using is:

mylist = (re.split("[\t\n]+",outputstring))

Try this list comprehension:

a="""a,b,c,d,e
f,g,h,i,j
k,l,m,m,o"""
mylist=[e.split(",") for e in a.split("\n")]

I'm very sorry, but if it is not an obligatory to use regex, can't you just do this?

my_list = [line1.split(','), line2.split(','), line3.split(',')]

or this

initial_list = []

initial_list.append(line1)
initial_list.append(line2)
initial_list.append(line3)

final_list = [x.split(',') for x in initial_list]

I know you surely have not only 3 lines, but if you can do ["a,b,c,d,e,f,g,h,j,k,l"] with your output, maybe you can do this as well.

You can also do it using the map function:

output = """a,b,c,d,e
f,g,h,i,j
k,l,m,m,o"""

output = list(map(lambda i: i.split(','), output.split('\n')))
print(output)

Output:

[['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h', 'i', 'j'], ['k', 'l', 'm', 'm', 'o']]

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