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"']
Related
i have two list i want to have concatenation without additional quote ,and those lists that i want to enter
a=["a"]
b=["b"]
** how i can pass it in matrix like this**
matrix["ab"]
** or how i can get this result , i try append and concatenate but it doesn't work**
c=["ab"]
Use
d = list([a[0]+b[0]])
or use the code below which also combines strings from longer lists such as ['a', 'c'] and ['b', 'e']
d = [i+j for i, j in zip(a,b)]
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(','))
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]
Input Format :
The first line of input is an integer that corresponds to the number of records, 'n'.
The next 'n' line corresponds to the records.
The last line of input consists of the date to be filtered.
Output format :
The first line of the output is a set of comma seperated strings containing the cargo name and date.
The next lines consists of the names of the cargos printed one next to the other seperated by new line.
Refer to sample input and output for formatting specifications and more details.
Sample Input 1:
5
Allegan,11-12-2013
Douglas,29-12-2016
Junkers,27-03-2017
Biruinta,10-04-2014
ABC,27-03-2017
27-03-2016
Expected Sample Output 1:
[('Allegan', '11-12-2013'), ('Douglas', '29-12-2016'), ('Junkers', '27-03-2017'), ('Biruinta', '10-04-2014'), ('ABC', '27-03-2017')]
Douglas
Junkers
ABC
Code that was written:
n=int(input())
list1=[]
i=0
for i in range(0,n):
string1=raw_input()
i+=1
string1=string1.split()
for item in string1:
list1.append(item)
dateformat=raw_input()
mutuple = tuple(list1)
I am unable to split input from my list and get desired output by comparing as per the question. Can you please help
You can pass the delimiters to the split function:
In [1]: "a,b,c,d,e,f".split(",")
Out[1]: ['a', 'b', 'c', 'd', 'e', 'f']
I also wouldn't do string1=string1.split(), because the return of split is
a list and the variable is called string. Sure it's not incorrect, but that
might confuse you later more than it helps.
Also
for item in string1:
list1.append(item)
...
mutuple = tuple(list1)
is redundant, you just can do mutuple = tuple(string1). But that's not
probably what you want.
long_list = []
ls = tuple("a,b".split(","))
long_list.append(ls)
ls = tuple("c,d".split(","))
long_list.append(ls)
print long_list
# prints [('a', 'b'), ('c', 'd')]
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.