Reputation: 29
I have a list that contains floats and strings ex: [1.456, 'upn', 7.965, 'bvb'] How can I separate these into two lists that would read [1.456, 7.95] and ['upn' , 'bvb']
Upvotes: 1
Views: 138
Reputation: 122112
If you have more than strings and float, you can try sorting the elements in a list by their type(x)
, see http://docs.python.org/2/library/types.html:
>>> from collections import defaultdict
>>> lst = [1.456, 'upn', 7.965, 'bvb']
>>> ddict = defaultdict(list)
>>> for i in lst:
... ddict[type(i)].append(i)
...
>>> for i in ddict:
... print i, ddict[i]
...
<type 'float'> [1.456, 7.965]
<type 'str'> ['upn', 'bvb']
Upvotes: 0
Reputation: 5275
>>> mixed_list = [1.456, 'upn', 7.965, 'bvb']
>>> temp_list = sorted(mixed_list)
>>> output_tuple = next( (temp_list[:temp_list.index(i):1],temp_list[temp_list.index(i):]) for i in temp_list if type(i) == str)
>>> output_tuple[0]
[1.456, 7.965]
>>> output_tuple[1]
['bvb', 'upn']
>>> sorted(mixed_list)
[1.456, 7.965, 'bvb', 'upn']
Here first I have sorted the list which arranges them in float and string order.
Then I have used next as iterator to check for first occurrence of 'string' and as soon as I get string the iterator will stop and give us the result.
It seems little complicated but it is faster then other methods where you have to iterate over whole list.
It can be very efficient if you have a big input list.
Upvotes: 0
Reputation: 34146
One way would be using slicing some_list[start:end:step]
:
b = a[::2]
c = a[1::2]
print b
print c
Output:
[1.456, 7.965]
['upn', 'bvb']
Note: This approach will only work if the list follows the pattern [float, str, float, str...]
Upvotes: 2
Reputation: 10850
For Python 2.x:
lst = [1.456, 'upn', 7.965, 'bvb']
[i for i in lst if isinstance(i, basestring)]
[i for i in lst if isinstance(i, float)]
For Python 3.x:
lst = [1.456, 'upn', 7.965, 'bvb']
[i for i in lst if isinstance(i, str)]
[i for i in lst if isinstance(i, float)]
Output:
['upn', 'bvb']
[1.456, 7.965]
Upvotes: 3
Reputation: 11039
float_list = []
string_list = []
for item in first_list:
if isinstance(item, float):
float_list.append(item)
elif isinstance(item, str):
string_list.append(item)
Upvotes: 3
Reputation: 9323
filter(lambda x:type(x) == str,[1.456, 'upn', 7.965, 'bvb'])
filter(lambda x:type(x) == float,[1.456, 'upn', 7.965, 'bvb'])
Upvotes: 1