Home > database >  How, can I put individual elements of a list into nested list in Python?
How, can I put individual elements of a list into nested list in Python?

Time:03-26

How can I take a list in the form of:

hostnames = ['Pam: 5, 10, 4', Pet: 3, 2', 'Sara: 44, 40, 50']

and convert it into a form like :

   hostnames = [[pam,5, 10, 4], [Pet,3, 2], [Sara,44, 40, 50]]

the end goal is so the code can print something like:

 [[pam,5, 10, 4], [Pet,3, 2], [Sara,44, 40, 50]]
 pam has scores of 5, 10 ,4
 pet has scores of 3, 2
 sara has scores of 44, 40, 50

my current code to help is this:

pos = 0
for var in hostnames:
    newlist = hostnames[pos]
    newlist = [newlist]
    pos = pos   1
    names = newlist[0]
    print(newlist)

I know the code asks for changes made to a new list, but I want this change made to the old hostname list. Without using the .Split Function

CodePudding user response:

IIUC, you need to use str.split method to split the strings; first split on : to separate "key"; then again on , to separate the integers:

out = []
for var in hostnames:
    k,v = var.split(':')
    out.append([k, *map(int, v.split(','))])

Output:

[['Pam', 5, 10, 4], ['Pet', 3, 2], ['Sara', 44, 40, 50]]

Perhaps you're looking for something along the lines of:

for var in hostnames:
    i = var.find(':')
    print("{} has scores of{}".format(var[:i], var[i 1:]))

Output:

Pam has scores of 5, 10, 4
Pet has scores of 3, 2
Sara has scores of 44, 40, 50

CodePudding user response:

Alternative solution is the following:

hostnames = ['Pam: 5, 10, 4', 'Pet: 3, 2', 'Sara: 44, 40, 50']

lst_items = [_.split(": ") for _ in hostnames]

for item in lst_items:
    print(f'{item[0]} has scores of {item[1]}')

Prints

Pam has scores of 5, 10, 4
Pet has scores of 3, 2
Sara has scores of 44, 40, 50
  • Related