0
How to make sublist form given list in python
rollno =[1,2,3,4,5] name = ['devang', 'pratham', 'dev', 'rohit', 'daxesh'] how can i make sublist which contains data =[ [1,'devang'] ,[2,'prathan']......etc
10 Réponses
+ 6
sublist = list(zip(rollno, name))
With that technique, the inner containers will be tuples, but if you insist on lists, you can write:
sublist = [[a, b] for a, b in zip(rollno, name)]
+ 4
subdict = {a: b for a, b in zip(rollno, name)}
+ 3
Zip takes an arbitrary number of iterables and constructs a plan for how they will be mixed.
You can for example take lists, strings, or whatever, and zip will connect the 1st, 2nd, 3rd, and so on items to tuples and hand them out. As soon as one of them ends, it will stop, so you won't get an error.
So if for example you write...
for t in zip('123', 'abc'):
print(t)
... you'll get the output:
('1', 'a')
('2', 'b')
('3', 'c')
+ 2
You could:
Create an empty list.
Iterate i from 0 to 5.
In each iteration you'd create a list of 2 items:
rollno[i] and name[i]
And append the list to the "empty list".
+ 2
You could:
Create an empty dictionary.
Iterate i from 0 to 5.
In each iteration you'd assing the "empty dictionary" index:
rollno[i]
to:
name[i]
+ 2
[[rollno[i], name[i]] for i in range(rollno)]
+ 1
https://code.sololearn.com/cD5GD3bMI4k9/?ref=app
0
If i want to write this in dictionary form how can i write ???
0
Sir can you explain how this zip function actually works???