Taking Elements From a List - python

I want to take an element of a list and remove the final character. The overall aim being to convert the number remaining from str to int for an equation. I thought this:
hand = ['1D', '5S', '10H']
first_card = hand [0]
first_card [:-1]
print [first_card]
...was the way to do so, but apparently not.
Thanks in advance for any help provided.
Frazer

This can be accomplished for all elements with a list comprehension.
>>> hand = ['1D', '5S', '10H']
>>> hand2 = [i[:-1] for i in hand]
>>> hand2
['1', '5', '10']
You can also easily convert this to ints at the same time:
>>> handints = [int(i[:-1]) for i in hand]
>>> handints
[1, 5, 10]

In case if the string contains multiple characters towards the ending.
from itertools import takewhile
map(lambda x: "".join(list(takewhile(lambda x: x.isdigit(),x))), ['1D', '5S', '10H'])
Or using a list comprehension
[int("".join(list(takewhile(lambda x: x.isdigit(),x)))) for x in ['1D', '5S', '10H']]

use map to solve trivial operations on every element in a list:
list(map(lambda x: x[:-1],hand))

Related

splitting a list in a better way using list comprehension

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']

Making multiple output lists into one list (python)

I have this generator
def keys():
objects = [{'1':True,'2':True,'3':False,'4':False,'5':True,'6':True}]
rng = range(len(objects))
clean = int(''.join(map(str, rng)))
for keys, values in objects[clean].iteritems():
if values == True:
yield keys
and then i want to get all the generator values, which I do using for loop
for i in keys():
i= i.split()
print i
and the output is :
['1']
['2']
['5']
['6']
is there a way I can add them to a single list?
like [['1'],['2'],['5'],['6']] or most preferably ['1','2','5','6'].
Would greatly appreciate your help. Thanks
You can just convert it to a list directly, as list takes an iterable;
out = list(keys())
Or if you want to, you could use a list comprehension;
out = [key for key in keys()]
This would make it easier to filter out certain items from the generator using the [for x in y if z] syntax.
Both output;
>>> print(out)
['2', '6', '1', '5']
Like this?:
my_list = []
for i in keys():
my_list.append(i.split())
print my_list
It would be a list comprehension like this if you want it as similar as possible to your original answer:
list = [key.split() for key in keys()]
print(list)

why sort in python is not working?

code:
list=['1','85863','432','93','549834']
list.sort()
print (list)
Actual output:
>>>
['1', '432', '549834', '85863', '93']
#why sort is not working
Expected output:
['1','93','432','83863','549834']
I have tried other sort operations also but they are displaying same output.
when i tried to read list from keyboard input they are reading only strings but not int please help me why?
when i tried to read list from keyboard input they are reading only strings but not int please help me why
if x is a string, just use int(x) to convert to int
You're sorting strings (text), not by numerical values like integers
For your expected output you have to convert to ints first
my_list= ['1','85863','432','93','549834']
my_list = [int(x) for x in my_list]
Now you can sort numerically, and get a list of ints
my_list.sort()
N.B. avoid using list as variable name, it is a Python built-in
I presume you want to sort by the sum to match your expected output:
l = ['1','85863','432','93','549834']
l.sort(key=lambda x: sum(map(int,x)))
print(l)
['1', '432', '93', '83863', '549834']
You need to first convert the strings to int.
list = [int(ele) for ele in list]
list.sort()
print list
Without int:
lst = ['1','85863','432','93','549834']
lst.sort()
lst.sort(key=len)
print(lst)
This give:
['1', '93', '432', '85863', '549834']
And if you want integers…
my_int = int(input())
I simply missed the logic of converting a string into int.By default python input will be taken as a string. so,we can use any method mentioned in the answers to convert in to string and then sort() method works succesufully over int

Converting an integer list into a string list

I am new to Python. I need to know how to convert a list of integers to a list of strings. So,
>>>list=[1,2,3,4]
I want to convert that list to this:
>>>print (list)
['1','2','3','4']
Also, can I add a list of strings to make it look something like this?
1234
You can use List Comprehension:
>>> my_list = [1, 2, 3, 4]
>>> [str(v) for v in my_list]
['1', '2', '3', '4']
or map():
>>> str_list = map(str, my_list)
>>> str_list
['1', '2', '3', '4']
In Python 3, you would need to use - list(map(str, my_list))
For 2nd part, you can use join():
>>> ''.join(str_list)
'1234'
And please don't name your list list. It shadows the built-in list.
>>>l=[1,2,3,4]
I've modified your example to not use the name list -- it shadows the actual builtin list, which will cause mysterious failures.
Here's how you make it into a list of strings:
l = [str(n) for n in l]
And here's how you make them all abut one another:
all_together = ''.join(l)
Using print:
>>> mylist = [1,2,3,4]
>>> print ('{}'*len(mylist)).format(*mylist)
1234
l = map(str,l)
will work, but may not make sense if you don't know what map is
l = [str(x) for x in l]
May make more sense at this time.
''.join(["1","2","3"]) == "123"

Difference between list of lists

I have two lists
A=[['1','1'],['2','1'],['3','2']]
B=[['1','1'],['2','2']]
I want to perform A-B operation on these comparing only first element.
so A-B should give
Output=[['3', '2']]
So far, I could do only on row comparison
[x for x in A if not x in B]
which gives output as [['2', '1'], ['3', '2']]
This?
>>> [i for i in A if not any(i[0] == k for k, _ in B)]
[['3', '2']]
any() is used to check if the first element of each list is the same as any other value in every list in B. If it is, it returns True, but as we want the opposite of this, we use not any(...)
You can also use collections.OrderedDict and set difference here:
>>> from collections import OrderedDict
>>> dic1 = OrderedDict((k[0],k) for k in A)
>>> [dic1[x] for x in set(dic1) - set(y[0] for y in B)]
[['3', '2']]
Overall complexity is going to be O(max(len(A), len(B)))
If order doesn't matter then a normal dict is sufficient.
I could think of a different list comprehension
A=[['1','1'],['2','1'],['3','2']]
B=[['1','1'],['2','2']]
b = dict(B)
output_list = [item for item in A if item[0] not in b]
This is order preserving as well and can work even if there are duplicate fist elements in the inner list of A. Also it can be extended to check for exact pair if needed like this:
A=[['1','1'],['2','1'],['3','2']]
B=[['1','1'],['2','2']]
b = dict(B)
output_list = [item for item in A if item[0] not in b or b[item[0]] != item[1]]

Categories