How do I remove hyphens from a nested list? - python

In the nested list:
x = [['0', '-', '3', '2'], ['-', '0', '-', '1', '3']]
how do I remove the hyphens?
x = x.replace("-", "")
gives me AttributeError: 'list' object has no attribute 'replace', and
print x.remove("-")
gives me ValueError: list.remove(x): x not in list.

x is a list of lists. replace() will substitute a pattern string for another within a string. What you want is to remove an item from a list. remove() will remove the first occurrence of an item. A simple approach:
for l in x:
while ("-" in l):
l.remove("-")
For more advanced solutions, see the following: Remove all occurrences of a value from a Python list

Related

Delete even indexes out of range [duplicate]

I'm trying to remove the odd-indexed elements from my list (where zero is considered even) but removing them this way won't work because it throws off the index values.
lst = ['712490959', '2', '623726061', '2', '552157404', '2', '1285252944', '2', '1130181076', '2', '552157404', '3', '545600725', '0']
def remove_odd_elements(lst):
i=0
for element in lst:
if i % 2 == 0:
pass
else:
lst.remove(element)
i = i + 1
How can I iterate over my list and cleanly remove those odd-indexed elements?
You can delete all odd items in one go using a slice:
del lst[1::2]
Demo:
>>> lst = ['712490959', '2', '623726061', '2', '552157404', '2', '1285252944', '2', '1130181076', '2', '552157404', '3', '545600725', '0']
>>> del lst[1::2]
>>> lst
['712490959', '623726061', '552157404', '1285252944', '1130181076', '552157404', '545600725']
You cannot delete elements from a list while you iterate over it, because the list iterator doesn't adjust as you delete items. See Loop "Forgets" to Remove Some Items what happens when you try.
An alternative would be to build a new list object to replace the old, using a list comprehension with enumerate() providing the indices:
lst = [v for i, v in enumerate(lst) if i % 2 == 0]
This keeps the even elements, rather than remove the odd elements.
Since you want to eliminate odd items and keep the even ones , you can use a filter as follows :
>>>filtered_lst=list(filter(lambda x : x % 2 ==0 , lst))
this approach has the overhead of creating a new list.

List, Convert Str List, replace values, print new str List. Should return ['*', '2', '3', '*', '5']

can any of you help me to identify what am I doing wrong? I know this might be simple but I
am new to programming and Python. I need to return ['*', '2', '3', '*', '5']. Instead of that I am
getting much more values within the list.
Test to replace values in a List
repl_list = [1, 2, 3, 1, 5]
str_repl_list = str(repl_list)
# print('This is the list to replace: ' + str_repl_list)
# print(type(str_repl_list[0]))
new_str_list = []`enter code here`
print(new_str_list)
for item in str_repl_list:
replacement = item.replace('1', '*')
new_str_list.append(replacement)
for index, char in enumerate(new_str_list):
print(index, char) # This is to identify what information is being taken as par of the new list
when you do a str(repl_list), the outpt is a string '[1, 2, 3, 1, 5]', not a list of strings, so if you iterate through str_repl_list you will get
1
,
2
,
3
,
1
,
5
]
Instead you can avoid that step and convert each item to string inside your for loop (str(item))
repl_list = [1, 2, 3, 1, 5]
new_str_list = []
for item in repl_list:
replacement = str(item).replace('1', '*')
new_str_list.append(replacement)
>>> print(new_str_list)
>>> ['*', '2', '3', '*', '5']
you can also use list coprehension
>>> print(['*' if x == 1 else str(x) for x in repl_list])
>>> ['*', '2', '3', '*', '5']
Instead of converting each item to string, you are converting the entire list into a string. Instead try this list comprehension:
str_repl_list = [str(i) for i in str_list]
This will go through each item and convert it into a string, then store it in the new list.
since you are appending each element in the list new_str_list, to see the desired result you need to print them together, so you need to join them in a string and add all element in the string.
so to see the desired result, you just need to add all elment together
which can be done as
str_list_final = ''.join(new_str_list)

max method of a list consisting of strings

I am wondering why the result is '4' if I write the following code:
lists = ['1','2','3','4']
print(max(lists))
lists.append(5)
print(max(lists))
I suppose that the max method of lists converts from str to int first and then gives me the max of ints in the first couple of lines, but this seems untrue if I try the next lines. Can anyone explain this?
Your list contains strings and you are appending an integer.
lists = ['1', '2', '3', '4', 5]
TypeError: '>' not supported between instances of 'str' and 'int'
If you had only strings or only int's max will do the comparison as the '>' operator will work. You need to convert the list to all strings or all ints.
lists = [int(x) for x in lists] #by list comprehension
>>> max(lists) # lists= [1, 2, 3, 4, 5]
>>> 5
lists = [str(x) for x in lists]
>>> max(lists) # lists = ['1', '2', '3', '4', '5']
>>> '5'
If you have not yet seen list comprehensions it's doing this but much faster and in a single line of code.
new_list = []
for x in lists:
x = int(x) #convert each individual term to integer objects
new_list.append(x)
lists = new_list
Actually, it doesn't give you TypeError it will return '4' for both cases below:
list = ['1', '2', '3', '4']
list = ['1', '2', '3', '4', 5]
because when comparing objects in python, str always > int that's why you are getting '4' as the max value because it is the highest value among the strings
here is an example to prove what I'm saying:
>print '1' > 5
True
>print '1' > '5'
False
You can try this:
lists = ['1','2','3','4']
print(max(list(map(int, lists))))
lists.append(5)
print(max(list(map(int, lists))))

How to remove preceding zeros in a string element from a Python list

I have a list:
my_list = ['0300', '0023', '0005', '000030']
I want to remove the preceding zeroes in each string element from the list. So I want strip the 0s from the left side of the string.
Output would be like this:
my_list = ['300', '23', '5', '30']
I've tried this:
for x in my_list:
x = re.sub(r'^0+', "", x)
print my_list
But it doesn't seem to work. Please help!
You can use str.lstrip like this
print [item.lstrip('0') for item in l]
# ['300', '23', '5', '30']
Try:
list = [str(int(el)) for el in list]
Edit: pick the other answer, I'd prefer that one too :-)

How to remove specific strings from a list

From the following list how can I remove elements ending with Text.
My expected result is a=['1,2,3,4']
My List is a=['1,2,3,4,5Text,6Text']
Should i use endswith to go about this problem?
Split on commas, then filter on strings that are only digits:
a = [','.join(v for v in a[0].split(',') if v.isdigit())]
Demo:
>>> a=['1,2,3,4,5Text,6Text']
>>> [','.join(v for v in a[0].split(',') if v.isdigit())]
['1,2,3,4']
It looks as if you really wanted to work with lists of more than one element though, at which point you could just filter:
a = ['1', '2', '3', '4', '5Text', '6Text']
a = filter(str.isdigit, a)
or, using a list comprehension (more suitable for Python 3 too):
a = ['1', '2', '3', '4', '5Text', '6Text']
a = [v for v in a if v.isdigit()]
Use str.endswith to filter out such items:
>>> a = ['1,2,3,4,5Text,6Text']
>>> [','.join(x for x in a[0].split(',') if not x.endswith('Text'))]
['1,2,3,4']
Here str.split splits the string at ',' and returns a list:
>>> a[0].split(',')
['1', '2', '3', '4', '5Text', '6Text']
Now filter out items from this list and then join them back using str.join.
try this. This works with every text you have in the end.
a=['1,2,3,4,5Text,6Text']
a = a[0].split(',')
li = []
for v in a:
try : li.append(int(v))
except : pass
print li

Categories

Resources