If statement that keeps characters only - python

Let's say we have a list list_a = [a,b,C,.,/,!,d,E,f,]
i want to append to a new list only the letters of the alphabet.
So the new list will be list_b = [a,b,C,d,E,f].
So far i have tried doing it like that way:
list_b = []
for elements in list_a:
try:
if elements == str(elements):
list_b.append(elements)
except ValueError: #Catches the Error when the element is not a letter
continue
However, when i print the list_b it has all the elements of list_a , it doesn't do the job i expected.
Any ideas ?
PS: comma in the specific example brings Error too.

You can use the .isalpha() method of the string type.
In [1]: list_a = ['a','b','C','.','/','!','d','E','f']
In [2]: list_b = [i for i in list_a if i.isalpha()]
In [3]: list_b
Out[3]: ['a', 'b', 'C', 'd', 'E', 'f']

Try checking if the character is an alphabet by using the .isalpha() function.
list_b = []
for elements in list_a:
if elements.isalpha():
list_b.append(elements)

You are missing the fact that the str() function does not return the "str" elements you think it does, just an str representation of them.
Try creating a list with you dictionary [a-zA-Z] (not very pythonic but simple to grasp) and check if your character exists in it.
I suggest writing your own code from scratch instead of copy/pasting, that is the only way to really understand the problem....

You can try this:
import string
for item in list_a:
if item in string.ascii_letters:
list_b.append(item)
Also, check out the string module. It has a lot of additional methods that can help you, should you wish to work with strings. Do note that this works only with ascii characters. If you want to check for every character in an alphabet, then you can via the isalpha() method, as the others have noted above.

Well, it is basically the same logic of using isalpha() method, but you can do this by using filter:
list_a = ['a','b','C','.','/','!','d','E','f']
list_b = list(filter(lambda i: i.isalpha(), list_a))
print(list_b)
Output:
['a', 'b', 'C', 'd', 'E', 'f']

You can use the string or re package to do this
import re
new_list = [c for c in old_list if re.match(r'[a-zA-Z]', c)]
Or with string
import string
new_list = [c for c in old_list if c in string.ascii_letters]

Related

Python tKinter adds apostrophe to list

I'm working on an Python script with a GUI.
I can read out some colors using get().
The problem is that when I want to use these colors to draw shapes using PIL, Python adds apostrophes to the beginning and end of the list.
def add_color_lines():
the_color=tab_lines_colors_input.get()
lines_color_list.append(the_color)
print(lines_color_list)
This is the output:
'"white","black","grey"'
I want it to be:
"white","black","grey"
What am I doing wrong?
Why does the script add apostrophes to the list?
This is what I add:
This is what I get. Notice the apostrophes next to the brackets.
PIL cannot work with this because it says:
ValueError: unknown color specifier: '"white","black","grey"'
You can parse the string it's giving with the split() function.
output = lines_color_list.split(",")
This should output this list
['"white"', '"black"', '"gray"']
Alright, as mentioned by #acw1668 when you get the input form the text, it should just be color without quotes. white,black,grey
Now, in change the code to use the_color.split(",") and append that values to the list using lines_color_list += the_color.split(",")
lines_color_list = []
def add_color_lines():
global lines_color_list
the_color=tab_lines_colors_input.get()
lines_color_list += the_color.split(",")
print(lines_color_list)
The reason of apostrophe/single quote (') is how print function prints string elements of a list. Try this out to see how it prints.
Sample 1:
# Three elements in a list
my_list = ["a", "b", "c"]
print(my_list)
output
['a', 'b', 'c']
Sample 2:
# Three element in a list
my_list = ['a', 'b', 'c']
print(my_list)
output
['a', 'b', 'c']
Sample 3:
# One element in a list
my_list = ["a, b, c"]
print(my_list)
output
['a, b, c']
Sample 4 (your current scenario):
my_list = []
my_text = '"a", "b", "c"'
my_list.append(my_text) # Single element in the list
print(my_list)
output
['"a, b, c"']

How to delete all elements only that i want?

I'm really beginer of python and i'm wondering how to remove all same elements that i want
I know i can remove a one element with list.remove('target') but it just happen once,
I googled about it but they just say use 'for' or 'while' but i don't know how to do it with a smart way
example , when i have list "apple" i want to make it "ale" with parameter'p'
I tried
list = ['a','p','p','l','e']
for i in list:
list.remove('p')
but i got error that 'ValueError: list.remove(x): x not in list'
(My English might sucks because i'm Korean :( and it's my first ask in stackoverflow )
First you should not be using list as a variable name as list is a built-in type in python.
See: Built-in types in python
For your question, you can use list comprehension for this.
eg:
my_list = ['a','p','p','l','e']
element_to_remove = 'p'
new_list = [item for item in my_list if item != element_to_remove]
# new_list = ['a', 'l', 'e']
You can convert the list to set (so that there will be no repetitions) and convert it back to list. After, remove the element you want.
my_list = ['a','p','p','l','e']
my_list2 = my_list(set(my_list))
my_list.remove('p')
Try list comprehension:
[i for i in l if i not in ('p',)]
where l is your list.

python: remove single quotation mark from elements in list. AttributeError: 'list' object has no attribute 'split'

from this list
lst=['a,b,c','d,e']
I want to obtain the following one
lst=['a','b','c','d','e']
so I assumed that first of all the quotation marks from the first list should be removed,
but this line
[i for i in lst.split(' ' ' ')]
produces this error message:
AttributeError: 'list' object has no attribute 'split'
How should I change my code to get what I need ?
I know I already answered, I just noticed that since the elements are strings and have comma separations, you could use str.join on the list then just str.split the result to get the desired output:
','.join(lst).split(',')
>>> lst = ['a,b,c','d,e']
>>> ','.join(lst).split(',')
['a', 'b', 'c', 'd', 'e']
Note this works in this case but only because of your particular values.
If you want to use a list comprehension, it'll look like this:
[y for x in lst for y in x.split(',')]
The error is because you're calling split on a list, but you need to call it on a str. The for x in lst gives you strings as x, which you then call split(',') on to get y, which is what goes into the final list.
This is equivalent to:
output = []
for x in lst:
for y in x.split(','):
output.append(y)
You should first iterate through each text in your lst list, split those texts on comma and then flatten the split text's characters into a list like this:
lst=['a,b,c','d,e']
character_lst = [char for text in lst for char in lst.split(",")
# character_list will contain ['a','b','c','d','e']
Using itertools.chain:
from itertools import chain
list(chain(*(s.split(',') for s in lst)))
or as a (slower) full functional variant:
from itertools import chain
list(chain(*map(lambda x: x.split(','), lst)))
output:
['a', 'b', 'c', 'd', 'e']
Without imports or nested loops:
lst = ['a,b,c','d,e']
output = []
for x in lst:
output.extend(x.split(','))

The condition skips 2 members of a list [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Modifying list while iterating
I have been given a task to make a code in python that will remove all members that occures more than once in a list and leave 1 copy of it.
Condition: it should be case-insesitive
So I've written down the following code:
string = raw_input()
list1 = string.split(",")
low_case_list = list1[:] #for case-insesitive
for i in range(len(low_case_list)):
low_case_list[i] = low_case_list[i].lower()
for member in low_case_list:
if(low_case_list.count(member) > 1):
del list1[low_case_list.index(member)]
del low_case_list[low_case_list.index(member)]
after the input I get this list: [a,b,c,d,A,B,C,D,a,b,c,d]
and after I do the operation on it: [B,D,a,b,c,d]
my question is, why it skips 'B' and 'D' when it removes the members?
Why not just convert your list into a set with all elements converted to lower-case, and then back to a list. You can use a generator for converting every element to lowercase.
You can do it like this: -
>>> l = ['a', 'b', 'c', 'A', 'B', 'C', 'a', 'b', 'c']
>>> new_list = list(set(elem.lower() for elem in l))
>>> new_list
['a', 'c', 'b']
Note that, order may be changed because, set does not maintain the order of it's elements.
You could try something like this instead:
input = raw_input().split(',')
unique = set([s.lower() for s in input])
result = list(unique)
Try this, should be simple.
Given your list li:
lowcase = [elem.lower() for elem in li]
output = []
for el in lowcase:
if el not in output: output.append(el)
return output # if necessary, otherwise a simple li = output
Or, in a faster and more elegant way, you could replace the whole for loop with:
[output.append(el) for el in lowcase if el not in output]
Your code should be buggy because you refer to the index of the element, but the list changes size during the loop, so indices change too.
EDIT: didn't think about sets, obviously they're the best solution here.

Splitting a list

I've scoured various resources and can't figure out how to do a rather simple operation.
Right now, I have a list as follows:
li = [['a=b'],['c=d']]
I want to transform this into:
li = [['a','b'],['c','d']]
As I understand it, split("=") only applies to string types. Is there an equivalent method for lists?
Pardon the simplicity of my question...
-Dan
You want this:
[x[0].split('=') for x in li]
# prints [['a', 'b'], ['c', 'd']]
To grab a question from a comment further down the post, the reason split works for x[0] is that x represents the inner list. That's accomplished by the for x in li. Also, I fixed mine to read for x in li and not for x in test as I had assigned your examples to a variable called 'test' on my system.
You can use map():
>>> li = [['a=b'],['c=d']]
>>> map(lambda x: x[0].split('='), li)
[['a', 'b'], ['c', 'd']]
This traverses the list li and applies the lambda function to every element. As every element of the list is again a list with one element, x[0] takes this element, which is a string, splits it and returns a new list with both values.
Warning - its been a while since I did any python, but your issue is more general.
You are correct in that split applies to strings.
What you need to do is split the VALUE contained in your list not the list itself.
So you would do something like
newValue = split('=', li[0][0])
li[0] = newValue
Is this what you are looking for ?
map(lambda y:y.split('='),map(lambda x:x[0], li))
You can do it with this:
[k[0].split("=") for k in li]
Presuming each sublist consists of individual strings of the form a=b:
>>> [el[i].split('=') for el in li for i in range(len(el))]
[['a', 'b'], ['c', 'd']]
(Indeed, what you're splitting is the inner string a=b. So the split() string method works fine.)
EDIT: A much more elegant way of doing this double list comprehension is:
>>> [a.split('=') for el in li for a in el]
[['a', 'b'], ['c', 'd']]
There have been a number of good suggestions made, so the OP should be able to learn a good amount of Python for it. Important to remember is that what is being split is li[i][j], ie an item of the list that is an item of the list li.

Categories