1

can you help me get output like this by using bellow data:

name='suraj,rohit,rahul'
score='34,45,55'

I want to make a list like this:

[['suraj', 34], ['rohit', 45], ['rahul', 55]]

Please help.

5 Answers 5

3

You can use:

list(zip(name.split(','), score.split(',')))

[('suraj', '34'), ('rohit', '45'), ('rahul', '55')]

EDIT

People wanted lists instead ot tuples and int instead of strings, here we go:

[[x, int(y)] for x, y in zip(name.split(','), score.split(','))]

[['suraj', 34], ['rohit', 45], ['rahul', 55]]

Sign up to request clarification or add additional context in comments.

2 Comments

to exactly match OP's expected output, maybe also map score to int :)
This is a list of tuples, not a list of lists and the score is not an integer
2

You can use list comprehension.

[[i,int(j)] for i,j in zip(name.split(','), score.split(','))]
#[['suraj', 34], ['rohit', 45], ['rahul', 55]]

Comments

1

Instead of using a list, you can use a dictionary in order to make it more efficient while making it work properly at the same time. Please refer to the following code I have provided below in order to make your program much more better. code:

 name=""
 score=""
 Dictionary={"suraj,":34,"rohit,":45,"rahul":55}
 for A,B in Dictionary.items():
     name=name+A
     score=score+str(B)+","
 print(name)
 print(score)

I hope this cleared your doubt

Comments

0

you can combine map() and zip() functions to get list of list,also to conver list of sting into list of integers:

name='suraj,rohit,rahul'
score='34,45,55'

print (list(map(list, zip(name.split(','), map(int,score.split(','))))))

output:

[['suraj', 34], ['rohit', 45], ['rahul', 55]]

you can also use basic for loop:

name='suraj,rohit,rahul'.split(',') # get list of names
score='34,45,55'.split(',') # get list of scores


result = []
for i in range(len(name)):
    result.append([name[i],int(score[i])])

print (result)

output:

[['suraj', 34], ['rohit', 45], ['rahul', 55]]

Comments

0

You can use a lambda function instead:

    print(list(map(lambda x,y: [x,y], name.split(','), score.split(','))))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.