AttributeError when filling empty list with strings [duplicate] - python

This question already has answers here:
Why does "x = x.append(...)" not work in a for loop?
(8 answers)
Closed 5 years ago.
I currently have a list
outcomes = [('A','B','C','A.B','A.C','B.C','A.B.C')]
and I am trying to loop over it. If one of the "name" in the list contains a A, then I want to create another list called column_names with that name in it.
For instance, if I am looking for As, my returning list would be:
column_names = ['A','A.B','A.C',A.B.C']
I have the following code:
column_names = []
for name in outcomes:
if 'A' in name:
column_names = column_names.append(name)
but it returns:
AttributeError: 'NoneType' object has no attribute 'append'
I checked and both column_names and outcomes are lists so I dont understand why.

my_list=list()
for i in outcomes:
for j in i:
if j.count('A') == 1:
my_list.append(j)
output:
['A', 'A.B', 'A.C', 'A.B.C']
in your code
you used column_names = column_names.append(name) you must use column_names.append(name) instead

Related

Complicated list comprehension [duplicate]

This question already has answers here:
Check if a given key already exists in a dictionary
(16 answers)
Closed 6 months ago.
Im trying to build a list through list comprehension in python.
What I have so far, and it works:
modified_list = [
{id: metadata}
for id, metadata in new_resource_map.items()
if id not in old_resource_map or metadata["lastModified"] != old_resource_map[id]["lastModified"]
]
My list called: modified_list
Every item in it is dictionary {id: metadata}
I want to add one more thing and it will look like that:
modified_list = [
{id: metadata}
for id, metadata in new_resource_map.items()
if id not in old_resource_map or metadata["lastModified"] != old_resource_map[id]["lastModified"] **or
metadata["infer_tags"] != old_resource_map[id]["infer_tags"]**
]
The problem is what the last part:
or metadata["infer_tags"] != old_resource_map[id]["infer_tags"]
The problem is not all of the files have that field ("infer_tags").
I wanna do this last thing only after I check if this field is existing.
Is anyone know to do that?
as Mechanic Pig suggests:
if id not in old_resource_map or metadata["lastModified"] != old_resource_map[id]["lastModified"] or
metadata.get("infer_tags", np.nan) != old_resource_map[id].get("infer_tags", np.nan)
Note that the default values used in the get() calls must not be valid values for infer_tags fields for this to be reliable.

Delete lists with same elements in this case words in a listbut in different order in Python [duplicate]

This question already has answers here:
Remove duplicated lists in list of lists in Python
(4 answers)
Closed 7 months ago.
I have this list for example but there are more elements in the problem
data = [['USD','PEN'], ['GFY' ,'ARG'], ['TFG','RSD'], ['PEN','USD'], ['GFT','RSD']]
How can I eliminate the elements of the list that are repeated but in a different order, in this case the ['PEN','USD'] would be eliminated because the ['USD','PEN'] already exists in Python
The idea is that we can check the existence by the sorted element.
You can achieve this like below.
You could make this more elegant.
data = [['USD','PEN'], ['GFY' ,'ARG'], ['TFG','RSD'], ['PEN','USD'], ['GFT','RSD']]
tmp = []
exists = set()
for x in data:
x_sorted = tuple(sorted(x))
if x_sorted not in exists:
tmp.append(x)
exists.add(x_sorted)
tmp
# [['USD', 'PEN'], ['GFY', 'ARG'], ['TFG', 'RSD'], ['GFT', 'RSD']]
data = [['USD', 'PEN'], ['GFY', 'ARG'], ['TFG', 'RSD'], ['PEN', 'USD'], ['GFT', 'RSD']]
def remove_entries(data, entry1, entry2): # define function
for entry in data: # for every entry in the list
if entry1 in entry and entry2 in entry: # if both entries are present
data.remove(entry) # remove
return data # return result
clear = remove_entries(data, "USD", "PEN")
print(clear)

Edit List in Python [duplicate]

This question already has answers here:
Apply function to each element of a list
(4 answers)
Closed 12 months ago.
I have a list of Full Names, where Forenames and Surnames are seperated by a comma, for example:
Authors = ['Shakespeare, William', 'Dafoe, Daniel', 'Pilcher, Rosamunde']
I need a new list that contains only the Surnames, not the Forenames:
AuthorsSurname = ['Shakespeare', 'Dafoe', 'Pilcher']
How can I get there? I tried to search the Authors list with
regexAuthors = re.compile(r',$')
AuthorsSurname = (regexAuthors.findall(Authors))
to match all entries until the comma and create a new list, but it says I cannot use "Authors" as an argument here because it is not a string.
(the linked topic did not help)
Authors = ['Shakespeare, William', 'Dafoe, Daniel', 'Pilcher, Rosamunde']
surname = [val.split(",")[0] for val in Authors]
# ['Shakespeare', 'Dafoe', 'Pilcher']

I am unable to assign 'students' to different lists [duplicate]

This question already has answers here:
"Least Astonishment" and the Mutable Default Argument
(33 answers)
Closed 3 years ago.
I want to group students into two different lists according to the subjects but the function is failing to create different lists. I am aware that the instance of the list created in both cases is the same but I am unable to find a workable solution to the same.
def add_tolist(name, students=[]):
students.append(name)
return students
idc306 = add_tolist('ram')
idc101 = add_tolist('shyam')
idc101 = add_tolist('deepa',idc101)
print idc101, idc306
The results should be :
['shyam', 'deepa'] ['ram']
But its printing :
['ram', 'shyam', 'deepa'] ['ram', 'shyam', 'deepa']
I think the problem was that your program treated the new list as not a distinct new copy, this will fix that.
def add_tolist(name, students=[]):
students1 = students.copy()
students1.append(name)
return students1
idc306 = add_tolist('ram')
idc101 = add_tolist('shyam')
idc101 = add_tolist('deepa',idc101)
print (idc101, idc306)
output: ['shyam', 'deepa'] ['ram']

Call Dictionary With Randomly Chosen Value as Name - TypeError [duplicate]

This question already has answers here:
Access to value of variable with dynamic name
(3 answers)
Closed 6 years ago.
I am using a function that assigns a variable to equal the value of a randomly chosen key. Here the type is string and print works.
def explore():
import random
random_key = random.choice(explore_items.keys())
found_item = explore_items[random_key]
print type(found_item)
print found_item
Then, I want to use the variable name 'found_item' to call a dictionary of the same name, eg:
print found_item['key_1']
But I get the error, "TypeError: string indices must be integers, not str"
How would I use a string to call a previously defined dictionary that shares the same name?
You can use a variable via its name as string using exec:
dic1 = {'k': 'dic2'}
dic2 = {'key_1': 'value'}
exec('print ' + dic1['k'] + "['key_1']")
Short answer: I don't think you can.
However, if the dictionary explore_items uses the dicts in questions as its keys, this should work.
ETA to clarify:
explore_items = {{dict1}: a, {dict2}:b, {dict3}:c}
random_key= random.choice(explore_items.keys())

Categories