How to remove characters from each element in a list - python

I would like to remove the first two characters from each element (which are currently ints) that i have in a list. This is what i have:
lst = [2011,2012,3013]
I would like to get this
lst= [11,12,13]
I do not want a solution with some sort of replace 20 or 30 with '' however.

Given source= [2011,-2012,-3013] :
Result as ints, unsigned:
dest = [abs(x)%100 for x in source]
Result as ints, signed
dest = [(abs(x)%100)*(1 if x > 0 else -1) for x in source]
Result as strings, unsigned (preserves leading zeroes):
dest = list(map(lambda x : str(x)[-2:],source)
Result as strings, signed (preserves leading zeroes):
dest = list(map(lambda x : ("-" if str(x)[0]=="-" else "")+str(x)[-2:],source))

You can use:
list = [abs(number)%100 for number in list]
And it's a bad practice to name lists list. Use another name.

You can use module by 100,like:
my_list= [2011,2012,3013]
expected_list = [i%100 for i in my_list]
If you have negative numbers in my_list:
expected_list=[abs(i)%100 for i in my_list]
Or use string slicing:
expected_list = [int(str(i)[2:]) for i in my_list] #[2:],because you want to remove first two numbers
Please try avoid using reserved keywords as you variable name, as you have used list as your variable name.

Modulo:
just modulo each element with like 100
list= [2011,2012,3013]
for i in range(len(list)):
list[i] %= 100

Related

Deleting list from a list of lists

I need to delete these lists inside of list that contains the / symbol.
List for example:
X = [['a/','$1'], ["c","d"]]
so X[0] should be deleted. The actual list are much longer and contains more instances of this condition.
I tried use something like:
print([l for l in X if l.count("/") <1])
But if I understand correctly because the / is attached to another symbol he is not counted.
Should I convert this list of lists to string, separate the / from another character, and then use the count function, or there is better solution?
One way to search "/" in each item in the sublists is to wrap a generator expression with any. Since you don't want sublists with "/" in it, the condition should be not any():
out = [lst for lst in X if not any('/' in x for x in lst)]
Output:
[['c', 'd']]
The call to filter() applies that lambda function to every list in X and filters out list with '/'.
result = list(filter(lambda l: not any('/' in s for s in l), X))
counter = 0
while counter < len(X):
removed = False
for i in X[counter]:
if '/' in i:
X.pop(counter)
removed = True
break
if not removed:
counter += 1
Given:
X = [['a/','$1'], ["c","d"]]
You can convert the sub lists to their repr string representations and detect the / in that string:
new_x=[sl for sl in X if not '/' in repr(sl)]
Or, you can use next:
new_x=[sl for sl in X if not next('/' in s for s in sl)]
Either:
>>> new_x
[['c', 'd']]

Trying to replace a list of strings consisting of integers into the sum of their digits- but running into type error

I have a list of strings consisting of integers, and I am trying to replace them with the sum of their digits. E.g. nums = ["12","23","33"] -> nums = [3,5,6]
Here is my code:
strng = ['12','23','33']
for i in range(len(strng)):
print(list((map(lambda x:int[x],list(strng[i])))))
For the above I am getting a TypeError: 'type' object is not subscriptable. It works up until map(), but when I add the list(map(...)), I get this error.
Any ideas how to fix it?
My after this is fixed, my idea is to do the following:
strng = ['12','23','33']
for i in range(len(strng)):
strng[i] = sum(list((map(lambda x:int[x],list(strng[i]))))))
Which should replace each of strng with the sum of its digits.
The error you're getting is you because you wrote int[x] instead of int(x). However, there are some additional issues with your existing solution.
The short and pythonic solution to this problem would be:
answer = [sum(map(int, list(s))) for s in strng]
To break this down:
[... for s in strng]: this is a list comprehension
list(s): This takes each string and converts it into a list of str of each character, so "123" becomes ["1","2","3"]
map(int, list(s)): This applys the int conversion to each element in list(s), so ["1","2","3"] becomes [1,2,3]
sum(...): We take the sum of the resulting list of ints
The equivalent of the above using a normal for loop would be something like this:
answer = []
for s in strng:
list_of_chars = list(s)
list_of_ints = map(int, list_of_chars)
sum_of_ints = sum(list_of_ints)
answer.append(sum_of_ints)
You can use comprehension, and iterate each digits, convert them to integer, finally pass it to sum builtin to get sum of the values.
>>> [sum(int(i) for i in v) for v in strng]
[3, 5, 6]
Not really efficient, but try this :
strng = ['12','23','33']
def function(strng) :
my_list = []
for string in strng :
my_list.append(0)
for digit in string :
my_list[-1] += int(digit)
return my_list
strng = function(strng)
print(strng)

Python: Appending the index number of a string item in a list to that item

For any given list of string items, e.g.
my_list = ['foo', 'bar', 'baz', 'foo']
How does one append the index number of each item to it's corresponding item in the list? Forming a new list with the format, e.g.
new_list = ['foo0', 'bar1', 'baz2', 'foo3']
My example list only has four items, but I'm interested in a generalised answer for an arbitrary number of string items (something that works as well for a list of 4,000 string items as it does for 4)
Cheers!
A simpler way:
new_list = [elm + str(index) for index, elm in enumerate(my_list)]
UPDATE: With Python 3.6+ and formatted strings literals you can get a more readable code:
new_list = [f'{elm}{index}' for index, elm in enumerate(my_list)]
A straight for loop would work:
counter = 0
new_list = []
for each_item in the_list:
new_list.append(each_item + str(counter))
counter += 1
A list comprehension with enumerate() would also be fine, but less readable:
new_list = [each_item + str(index) for each_item, index in enumerate(the_list)]
try this.
EDIT: Explanation: The function below takes a list as an input and returns a list with the element numbers appended to the item. The number appended to the end of each item in the list is padded with zeros based on the length of the input list. So a list of length 30 with have appended numbers 00 through 29; a list of 3901 will have appended numbers 0000 through 3900.
from numpy import log10
def numberedList(inlist):
i = 0
z = int(log10(len(inlist))) + 1
outlist = []
for element in inlist:
outlist.append(str(element) + str(i).zfill(z))
i = i + 1
return outlist
To create a list from a static list and a repeating list:
# need: ['A','B','C','First1','Middle1','Last1','First2','Middle2','Last2',...]
['A','B','C']+[s+str(n) for n in range(1,len(names)+1) for s in ['First','Middle','Last']]

Python - List.extend not returning expected value

I am trying to get a list all numbers divisible by three under 1000. I used this code:
y = []
for x in range(1000):
if not x % 3:
y.extend(str(x))
print y
However it simply returned a seemingly unordered list of integers under 10, repeated in no apparent order (If you would like to see this list just say, but it is very long and probably not useful). Does anyone know what I am doing wrong?
It is giving you the right numbers, it's just splitting them into individual characters.
Try list.append instead:
y.append(str(x))
Your meaning could be more explicit. It would make more sense to use x % 3 == 0 than not x % 3
This could also be summarised into a list comprehension:
y = [str(3 * i) for i in range(1000 / 3 + 1)]
Or, better yet (in my opinion), use map and range:
y = map(str, range(0, 1000, 3))
map applies the str function to every item in the list generated by range.
As pointed out in the comments, range creates a list of its own, the size of which depends on the length of the list. You can use xrange instead, to create an xrange object which can be used in the same way:
y = map(str, xrange(0, 1000, 3))
This avoids the creation of an intermediate list.
Your question is tagged python2.7 but note that in Python 3, the behaviour of range changes, so that it does what xrange does.
extend extends a list using another list. So when you try to extend a list using a string, it adds the digits of the number to the list.
>>> l = []
>>> l.extend(str(12))
>>> l
['1', '2']
The correct operator to use would be append, which appends a list to another list. But you should just do this instead:
y = [x for x in xrange(1000) if x%3 == 0] # use xrange in python2
Or just:
y = range(0, 1000, 3) # thanks to Sebastian for this
do:
y.append(str(x))
in place of
y.extend(str(x))
in case of extend, x considered to be list. For example, "123" considered as list with '1','2','3' as it's elements
Just another explanation and how to fix your snippet:
This is what list.extend says:
>>> help(list.extend)
Help on method_descriptor:
extend(...)
L.extend(iterable) -- extend list by appending elements from the iterable
>>>
In your case as string is iterable so it will iterable over your string and convert into a list of characters and extend to the original one.
So, we can fix your snippet using tuple or list instead of str:
Using single element tuple:
y = []
for x in range(1000):
if not x % 3:
y.extend((x,))
print y
Using single element list:
y = []
for x in range(1000):
if not x % 3:
y.extend([x])
print y

Python - Look in list for a item containing numbers

some_list = ['Name','Surname','R500']
some_list = ['Name','Surname','500']
how would if get the index of the item in the list that contains a number, in both cases I should get back index = 2
I was looking at something like:
some_list.index(r'%r' % '\d+')
You'll need to loop over the elements:
for i, x in enumerate(my_list):
if re.search(r"\d", x):
print i
If you're looking just for the first item containing a digit, this works without regular expressions and returns -1 (can be changed to whatever you want) if there is no element with digits:
next((i for i,n in enumerate(some_list) if any(c.isdigit() for c in n)), -1)

Categories