Edit List in Python [duplicate] - python

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']

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)

Append concatenates the strings instead of adding them to the list [duplicate]

This question already has answers here:
String concatenation without '+' operator
(6 answers)
Closed 1 year ago.
I want to return a list of strings, as shown below:
def get_regions():
normalized_regions = []
regions = [
"auckland"
"bay of plenty"
"canterbury"
"gisborne"
"hawkes bay"
"manawatu-whanganui"
"marlborough"
"northland"
"otago"
"southland"
"taranaki"
"tasman"
"waikato"
"wellington"
"west coast"
]
for r in regions:
normalized_regions.append(normalize_location(r))
return normalized_regions
normalize_location() is a function that converts the string to lowercase and removes unnecessary white spaces.
I don't understand why append() is concatenating the elements as single string instead of adding them to the list? Please see the screenshot below:
You're going to kick yourself.
It's because you haven't got a comma after each entry in the list.
Your list should be:
regions = [
"auckland",
"bay of plenty",
"canterbury",
"gisborne",
"hawkes bay",
"manawatu-whanganui",
"marlborough",
"northland",
"otago",
"southland",
"taranaki",
"tasman",
"waikato",
"wellington",
"west coast",
]

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']

Python: Create a number of empty Dictionaries from a file with unique name [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 3 years ago.
There are several ways of creating a empty Dictionary in Python, for example:
#method 1
Alan = {}
#method 2
John = dict()
I want to create a number of Dictionaries to store personal information of a group of employees. A person's name will be used as a unique name in creating the empty Dictionary. Employees name are stored into a file (info.txt) and each line will only have one name.
#info.txt
Alan
John
Fiona
... x Repeat N times
The number of name or entry in the file is unpredictable, so I wish to have a flexible code to handle this type of scenario.
My code will read every single line and try to create a empty Dictionary for each employee. However, my codes does not work because the Dictionary is not defined.
#read employee name from file
infoFile = open("info.txt","r")
#read every line and create Dictionary for each employee
for infoFileLine in infoFile:
if not infoFileLine.strip():
pass
else:
print("%s" %infoFileLine)
designFileLine = dict()
#update employee personal info
Alan["Age"] = 36
Alan["Height"] = 180
John["Age"] = 36
John["Height"] = 180
I am new to Python, so what is wrong with my code above? Or is there any other better way of doing it?
Thank you in advance.
You should make a master dictionary that contains other dictionarys. Here is a brief example:
master = {}
names = ["Alan", "Peter"]
for n in names:
master[n] = {}
print(master)
And the output is:
{'Alan': {}, 'Peter': {}}
Just change my names array for a file.readLines() method and it should work.

Categories