I have this List of lists containing string values:
List = [['138.314038', '-35.451642'],
['138.313946', '-35.45212'],
['138.313395', '-35.45291'],
['138.312425', '-35.453978'],
['138.311697', '-35.454879'],
['138.311042', '-35.45569'],
['138.310407', '-35.45647'],
['138.315603', '-35.44981'],
['138.315178', '-35.450241'],
['138.314603', '-35.450948'],
['138.314038', '-35.45164']]
I am trying to transform each string value in the list of lists into a float value.
I was trying:
results = [float(i) for i in List]
But I am only indexing the lists and not the values inside. How can I do it using a similar approach and keeping the same structure of the variable List.
You have list, so use a double comprehension:
results = [[float(i) for i in e] for e in List]
I am using numpy convert it
np.array(List).astype(float).tolist()
Out[185]:
[[138.314038, -35.451642],
[138.313946, -35.45212],
[138.313395, -35.45291],
[138.312425, -35.453978],
[138.311697, -35.454879],
[138.311042, -35.45569],
[138.310407, -35.45647],
[138.315603, -35.44981],
[138.315178, -35.450241],
[138.314603, -35.450948],
[138.314038, -35.45164]]
Maybe ugly using two list maps:
print(list(map(lambda x: list(map(float,x)), List)))
Output:
[[138.314038, -35.451642], [138.313946, -35.45212], [138.313395, -35.45291], [138.312425, -35.453978], [138.311697, -35.454879], [138.311042, -35.45569], [138.310407, -35.45647], [138.315603, -35.44981], [138.315178, -35.450241], [138.314603, -35.450948], [138.314038, -35.45164]]
Print it better:
pprint.pprint(list(map(lambda x: list(map(float,x)), List)))
Output:
[[138.314038, -35.451642],
[138.313946, -35.45212],
[138.313395, -35.45291],
[138.312425, -35.453978],
[138.311697, -35.454879],
[138.311042, -35.45569],
[138.310407, -35.45647],
[138.315603, -35.44981],
[138.315178, -35.450241],
[138.314603, -35.450948],
[138.314038, -35.45164]]
#you can use map function as well
results = [list(map(float,x)) for x in List]
you can expand the list, like this:
results = [list(map(float, l)) for l in List]
You could use map to achieve it.
floats = [ list(map(float, i)) for i in List ]
Related
I want to join the elements of two lists into one list and add some characters, like so:
list_1 = ['some1','some2','some3']
list_2 = ['thing1','thing2','thing3']
joined_list = ['some1_thing1', 'some2_thing2', 'some3_thing3']
however i don't know in advance how many lists I will have to do this for, i.e. I want to do this for an arbitrary number of lists
Also, I currently receive a list in the following form:
list_A = [('some1','thing1'),('some2','thing2'),('some3','thing3')]
so I split it up into lists like so:
list_B = [i for i in zip(*list_A)]
I do this because sometimes I have an int instead of a string
list_A = [('some1','thing1',32),('some1','thing1',42),('some2','thing3', 52)]
so I can do this after
list_C = [list(map(str,list_B[i])) for i in range(0,len(list_B)]
and basically list_1 and list_2 are the elements of list_C.
So is there a more efficient way to do all this ?
Try this if you are using python>=3.6:
[f'{i}_{j}' for i,j in zip(list_1, list_2)]
If you using python3.5, you can do this:
['{}_{}'.format(i,j) for i,j in zip(list_1, list_2)]
also you can use this if you don't want to use formatted string:
['_'.join([i,j]) for i,j in zip(list_1, list_2)]
You can join function like this on the base list_A, itself, no need to split it for probable int values:
list_A = [('some1','thing1',32),('some1','thing1',42), ('some2','thing3', 52)]
["_".join(map(str, i)) for i in list_A]
Output:
['some1_thing1_32', 'some1_thing1_42', 'some2_thing3_52']
Update:
For you requirement, where you want to ignore last element for last tuple in your list_A, need to add if-else condition inside the list-comprehension as below:
["_".join(map(str, i)) if list_A.index(i) != len(list_A)-1 else "_".join(map(str, i[:-1])) for i in list_A ]
Updated Output:
['some1_thing1_32', 'some1_thing1_42', 'some2_thing3']
For ignoring the last element of every tuple in list_A, I found this to be the quickest way:
["_".join(map(str, i)) for i in [x[:-1] for x in list_A] ]
I have a simple list that I am splitting and concatenating. My code uses for loop and if condition and ugly. Can you suggest a better way using list comprehension?
My code
mylist = ['10.10.10.1','10.10.10.2,10.10.10.3,10.10.10.4,10.10.10.5','10.10.10.6']
mylist = [i.split(",") for i in mylist]
list =[]
for x,y in enumerate(mylist):
if len(y) == 1:
list.append(y[0])
else:
for z in y:
list.append(z)
print(list)
I am getting the below result and exactly the way i want
['10.10.10.1','10.10.10.2','10.10.10.3','10.10.10.4','10.10.10.5','10.10.10.6']
You want:
[s for string in mylist for s in string.split(',')]
Note, your original approach wouldn't be so bad if you just simplified. No need for enumerate and no need to check the length, so just:
final_list =[]
for sub in mylist:
for s in sub:
final_list.append(s)
By the way, you shouldn't shadow the built-in list. Use another name
I agree with #juanpa.arrivillaga. However hope we can avoid that second looping since he is checking for empty values returning while splitting
In [7]: s=['10.10.10.1','','10.10.10.2,10.10.10.3,10.10.10.4,10.10.10.5','10.10.10.6']
In [8]: [splitRec for rec in s for splitRec in rec.split(',') if splitRec]
Out[8]:
['10.10.10.1',
'10.10.10.2',
'10.10.10.3',
'10.10.10.4',
'10.10.10.5',
'10.10.10.6']
In [9]: s=['10.10.10.1',',,','10.10.10.2,10.10.10.3,10.10.10.4,10.10.10.5','10.10.10.6']
In [10]: [splitRec for rec in s for splitRec in rec.split(',') if splitRec]Out[10]:
['10.10.10.1',
'10.10.10.2',
'10.10.10.3',
'10.10.10.4',
'10.10.10.5',
'10.10.10.6']
Not a comprehension, but good anyway, I think.
','.join(mylist).split(',')
You can first just split each string on ',':
>>> mylist = ['10.10.10.1','10.10.10.2,10.10.10.3,10.10.10.4,10.10.10.5','10.10.10.6']
>>> split_str = [x.split(',') for x in mylist]
>>> split_str
[['10.10.10.1'], ['10.10.10.2', '10.10.10.3', '10.10.10.4', '10.10.10.5'], ['10.10.10.6']]
Then if you want to flatten it, you can use itertools.chain.from_iterable:
>>> from itertools import chain
>>> list(chain.from_iterable(split_str))
['10.10.10.1', '10.10.10.2', '10.10.10.3', '10.10.10.4', '10.10.10.5', '10.10.10.6']
This might sound like a stupid question but I have the following list:
list = ['a','b','c','d','a','b','c','d']
And I want to get common elements together to rearrange it as:
sorted_list = ['a','a','b','b','c','c','d','d']
Is there any built in function in python to do that?
Well to get sorted list you could just use:
sorted_list = sorted(list)
which gives the output ['a','a','b','b','c','c','d','d']
To sort and group elements by values:
list = sorted(list)
sorted_list = [[y for y in list if y==x] for x in list]
which gives the output [['a','a'],['b','b'],['c','c'],['d','d']]
I have a Python list like:
['user#gmail.com', 'someone#hotmail.com'...]
And I want to extract only the strings after # into another list directly, such as:
mylist = ['gmail.com', 'hotmail.com'...]
Is it possible? split() doesn't seem to be working with lists.
This is my try:
for x in range(len(mylist)):
mylist[x].split("#",1)[1]
But it didn't give me a list of the output.
You're close, try these small tweaks:
Lists are iterables, which means its easier to use for-loops than you think:
for x in mylist:
#do something
Now, the thing you want to do is 1) split x at '#' and 2) add the result to another list.
#In order to add to another list you need to make another list
newlist = []
for x in mylist:
split_results = x.split('#')
# Now you have a tuple of the results of your split
# add the second item to the new list
newlist.append(split_results[1])
Once you understand that well, you can get fancy and use list comprehension:
newlist = [x.split('#')[1] for x in mylist]
That's my solution with nested for loops:
myl = ['user#gmail.com', 'someone#hotmail.com'...]
results = []
for element in myl:
for x in element:
if x == '#':
x = element.index('#')
results.append(element[x+1:])
l = ['1','2','3']
goal = ['<li>1</li>','<li>2</li>']
How can I get goal from l?
I'm playing with list comprehensions but it's messy!
Try string formatting and list comprehension, like so.
goal = ['<li>{0}</li>'.format(x) for x in l]
Two options using str.format():
goal = map('<li>{0}</li>'.format, l)
... or...
goal = ['<li>{0}</li>'.format(x) for x in l]
Note that on Python 3.x map() will return an iterator instead of a list, so if you want a list you would need to use list(map(...)).
With string.format method
goal = ['<li>{0}</li>'.format(sym) for sym in l]