Converting nested tuple into nested list in python - python

I have nested tuple like below wanted to convert into nested list in the format mentioned
Input:
T = [('id','1'),('name','Mike'),('Adrs','Tor')]
Output:
L = [['id','1'],['name','Mike'],['Adrs','Tor']]

>>> spam = [('id','1'),('name','Mike'),('Adrs','Tor')]
>>> eggs = [list(item) for item in spam]
>>> eggs
[['id', '1'], ['name', 'Mike'], ['Adrs', 'Tor']]

You could unpack each separate tuple and then append it
L = []
for item in T:
a, b = item
L.append([a,b])

l = [('id','1'),('name','Mike')]
m = [[], []]
for i in range(len(l)):
m[i] = [l[i][0], l[i][1]]
print(m)

Related

Join sublist in a list in python when the sublists are still items in the big list

I have a list like this:
l = [[1,4], [3,6], [5,4]]
I want to join the inner list with ":". I want to have the result as:
l = ['1:4', '3:6', '5:4']
How can I achieve it with Python?
You can use list comprehension to achieve this:
[':'.join(map(str, x)) for x in l]
l = [[1,4], [3,6], [5,4]]
fl = []
for x in l:
fl.append(str(x[0])+':'+str(x[1]))
print(fl) # Final List, also you can do: l = fl
But, i think that you want to do dictionaries, if this is true, you have to do:
l = [[1,4], [3,6], [5,4]]
fd = {}
for x in l:
fd[x[0]] = x[1]
print(fd) # Final Dictionary
EXPLANATION:
l = [[1,4], [3,6], [5,4]] # Your list
fl = [] # New list (here will be the result)
for x in l: # For each item in the list l:
fl.append(str(x[0])+':'+str(x[1])) # Append the first part [0] of this item with ':' and the second part [1].
print(fl)
With Dictionaries:
l = [[1,4], [3,6], [5,4]] # Your list
fd = {} # New dictionary
for x in l: # For each item in the list l:
fd[x[0]] = x[1] # Make a key called with the first part of the item and a value with the second part.
print(fd) # Final Dictionary
Also you can make a dictionary easier:
l = [[1,4], [3,6], [5,4]]
l = dict(l) # Make a dictionary with every sublist of the list (it also works with tuples), the first part of the sublist is the key, and the second the value.
You can do:
final_list = []
for i in l:
a = str(i[0])+':'+str(i[1])
final_list.append(a)
print(final_list)

Create a list of consequential alphanumeric elements

I have
char=str('DOTR')
and
a=range(0,18)
How could I combine them to create a list with:
mylist=['DOTR00','DOTR01',...,'DOTR17']
If I combine them in a for loop then I lose the leading zero.
Use zfill:
>>> string = "DOTR"
>>> for i in range(0, 18):
... print("DOTR{}".format(str(i).zfill(2)))
...
DOTR00
DOTR01
DOTR02
DOTR03
DOTR04
DOTR05
DOTR06
DOTR07
DOTR08
DOTR09
DOTR10
DOTR11
DOTR12
DOTR13
DOTR14
DOTR15
DOTR16
DOTR17
>>>
And if you want a list:
>>> my_list = ["DOTR{}".format(str(i).zfill(2)) for i in range(18)]
>>> my_list
['DOTR00', 'DOTR01', 'DOTR02', 'DOTR03', 'DOTR04', 'DOTR05', 'DOTR06', 'DOTR07', 'DOTR08', 'DOTR09', 'DOTR10', 'DOTR11', 'DOTR12', 'DOTR13', 'DOTR14', 'DOTR15', 'DOTR16', 'DOTR17']
>>>
You can do it using a list comprehension like so:
>>> mylist = [char+'{0:02}'.format(i) for i in a]
>>> mylist
['DOTR00', 'DOTR01', 'DOTR02', 'DOTR03', 'DOTR04', 'DOTR05', 'DOTR06', 'DOTR07', 'DOTR08', 'DOTR09', 'DOTR10', 'DOTR11', 'DOTR12', 'DOTR13', 'DOTR14', 'DOTR15', 'DOTR16', 'DOTR17']
Simply use list comprehension and format:
mylist = ['DOTR%02d'%i for i in range(18)]
Or given that char and a are variable:
mylist = ['%s%02d'%(char,i) for i in a]
You can, as #juanpa.arrivillaga also specify it as:
mylist = ['{}{:02d}'.format(char,i) for i in a]
List comprehension is a concept where you write an expression:
[<expr> for <var> in <iterable>]
Python iterates over the <iterable> and unifies it with <var> (here i), next it calls the <expr> and the result is appended to the list until the <iterable> is exhausted.
can do like this
char = str('DOTR')
a=range(0,18)
b = []
for i in a:
b.append(char + str(i).zfill(2))
print(b)

For loop inside another for loop Python

How do you add one list to another, I keep running into the problem of the second list in my for loop going through the whole list.
If aList was [1, 2, 3, 4], I want the output be 1hello, 2good, 3what... so on.
def function(aList):
myList = ['hello','good','what','tree']
newList = []
for element in aList:
for n in myList:
newList.append[element+n]
Input:
[1, 2, 3, 4]
Expected output:
['1hello', '2good', '3what', '4tree']
You want zip:
def function(aList):
myList = ['hello', 'good', 'what', 'tree']
return [str(a) + b for a, b in zip(aList, myList)]
Output:
In [4]: function([1, 2, 3, 4])
Out[4]: ['1hello', '2good', '3what', '4tree']
You also need to cast the passed in value to a string to make sure you can concatenate to the strings in your myList.
Read about List Comprehensions
aList = ['1', '2', '3']
print [element + n for element in aList for n in myList]
['1hello', '1good', '1what', '1tree', '2hello', '2good', '2what', '2tree', '3hello', '3good', '3what', '3tree']
or zip
aList = ['1', '2', '3']
print [element + n for element, n in zip(aList, myList)]
['1hello', '2good', '3what']
In Your question I feel no need to add two for loop. One loop itself sufficient.
let me give two cases, which one will match your need use that.
Case 1: - with one for loop
aList = [1,2,3,4]
def function(aList):
myList = ['hello','good','what','tree']
newList = []
for i in range(len(aList)):
newList.append(str(aList[i]) + myList [i] )
return newList
this will return 1hello , 2good ...
Case 2: - with two for loop
aList = [1,2,3,4]
def function(aList):
myList = ['hello','good','what','tree']
newList = []
for element in aList:
for i in range(len(myList )):
newList.append(str(element) + myList [i] )
return newList
this will return 1hello , 1good ... 2hello, 2good
I hope this will help...

'List of lists' to 'list' without losing empty lists from the original list of lists

Usually I would use a comprehension to change my list of lists to a list. However, I don't want to lose the empty lists as I will zip the final list to another list and I need to maintain the placings.
I have something like
list_of_lists = [['a'],['b'],[],['c'],[],[],['d']] and I use this
[x for sublist in list_of_lists for x in sublist]
which gives me
['a','b','c','d']
but what I would like is
['a','b','','c','','','d']
Sorry if this is a stupid question, I am new to python.
Thanks for any help!
Are you starting with the strings 'a', 'b', etc.? If so then you can use ''.join to convert ['a'] into 'a' and [] into ''.
[''.join(l) for l in list_of_lists]
Simply choose [''] instead of the empty list when presented with an empty sublist:
list_of_lists = [['a'],['b'], [], ['c'], [], [], ['d']]
[x for sublist in list_of_lists for x in sublist or ['']]
If you have some more complicated criteria for treating some sublists specially, you can use ... if ... else ...:
[x for sublist in list_of_lists for x in (sublist if len(sublist)%2==1 else [42])]
P.s. I'm assumig that the lack of quotes in the original is an oversight.
Something like:
a = b = c = d = 3
lol = [[a],[b],[],[c],[],[],[d]]
from itertools import chain
print list(chain.from_iterable(el or [[]] for el in lol))
# [3, 3, [], 3, [], [], 3]
>>> result = []
>>> for l in list_of_lists:
if len(l) >0:
result += l
else:
result.append('')
>>> result
['a', 'b', '', 'c', '', '', 'd']

Nested List and For Loop

Consider this:
list = 2*[2*[0]]
for y in range(0,2):
for x in range(0,2):
if x ==0:
list[x][y]=1
else:
list[x][y]=2
print list
Result:
[[2,2],[2,2]]
Why doesn't the result be [[1,1],[2,2]]?
Because you are creating a list that is two references to the same sublist
>>> L = 2*[2*[0]]
>>> id(L[0])
3078300332L
>>> id(L[1])
3078300332L
so changes to L[0] will affect L[1] because they are the same list
The usual way to do what you want would be
>>> L = [[0]*2 for x in range(2)]
>>> id(L[0])
3078302124L
>>> id(L[1])
3078302220L
notice that L[0] and L[1] are now distinct
Alternatively to save space:
>>> [[x,x] for x in xrange(1,3)]

Categories

Resources