I've got a list of full names from a csv file, but I only want to apply my next piece of code to the first names from that list. The list looks like this:
['michelle rodriguez', 'dexter king', 'gurukavari']
But then for a few thousand names. As you can see, some of the names don't contain a last name, and some do. How do I create a new list which contains only the first names from this list?
Use a list-comprehension:
lst = ['michelle rodriguez', 'dexter king', 'gurukavari']
print([x.split()[0] for x in lst])
# ['michelle', 'dexter', 'gurukavari']
You can use map function like:-
a = ['michelle rodriguez', 'dexter king', 'gurukavari']
b= map((lambda x: x.split()[0]), a) # ['michelle', 'dexter', 'gurukavari']
Would advise to use Map function, and to split each of the iterable items by space character, and return only the first of the split items.
Use a split function to separate the first name & last name from the name list and traverse the list till the last element.
Code :
names = ['michelle rodriguez', 'dexter king', 'gurukavari']
firstname = []
for i in range(0,len(names)):
firstname.append(names[i].split()[0])
print(firstname)
Output :
['michelle', 'dexter', 'gurukavari']
name = "Saurabh Chandra Patel"
first_name = name.rsplit(' ', 1)[0]
last_name = name.rsplit(' ', 1)[1]
first_name = Saurabh Chandra
last_name = Patel
if name = "Saurabh Patel"
first_name = Saurabh
last_name = Patel
Related
I need to get input from the user and check if the word following 'city' is inside of my dictionary (the key).
This is my dic:
mydic = {'Paris':132, 'Rome':42, 'San Remo':23}
I need the user to write 'city' (they will do so, given instructions that I gave them) but after it they have to write a city name. So they will write something like: 'city paris' and that has to return: 'Paris has 132 churches' or if they write 'city san remo' it has to return: 'San remo has 23 churches'.
The code has a conditional because if the user types 'city gba' then it returns a specific thing. So the issue is in the elif part where there are a lot more city options.
This is what I thought could work but doesn't for obvious reasons:
user_input = input().lower()
if user_input == 'city gba':
print('City gba has', city_data.get('gba'), 'churches')
elif user_input.split() == 'city' + '':
for x in user_input:
if x in mydic.keys():
print(x, 'has', city_data.get(x), ' churches.')
How else can I do this?
Thank you.
Your code is very close to working
user_input = input().lower() # Assume user input is "city Rome"
tag, city = user_input.split(" ", 1) # This will set tag = 'city' and city = 'rome'
if tag == 'city':
if city.capitalize() in mydic: # You could also do mydic.keys() it doesn't matter
print(f"{city} has {county_data.get(city)} churches.")
EDIT: .split() does not work as cities like united states or vatican city are separated by spaces. We should use .split(" ", 1) which will only split on the first occurrence of a space.
city, name = user_input.split(' ', 1) # Extract "city" and the city name
if name.lower() in mydic.keys():
print(x, 'has', county_data.get(x), ' churches.')
Note that you need the name and the key to be an exact match. I recommend that you drop both to lower-case for the comparison. Code the dict as all lower-case.
Your use-case is exactly the point of the new Python 3.10 feature Structural Pattern Matching. So your code could be rewritten to:
user_input = input().lower()
match user_input.split():
case ['city', 'gba']:
print('City gba has', city_data.get('gba'), 'churches')
case ['city', city]:
if city in mydict:
print(city, 'has', city_data[city], 'churches.')
Something as simple as this should work.
code
#prompt user for city name
city = input('Enter a city. Format \'city name\': ')
#split user input at spaces. #['city','cityName']
#take the second element in this list
city = city.split()[1]
#check if that city is in the given dictionary. If so we print the cities church count.
if city in mydic.keys():print(f'{city} has {mydic[city]} churches')
#if it is not visible in the dictionary we show that city is not located in the given dictionary
else:print('City not in dictionary')
input
Enter a city. Format 'city name': city Paris
output
Paris has 132 churches
In python I have a list of names, however some have a second name and some do not, how would I split the list into names with surnames and names without?
I don't really know how to explain it so please look at the code and see if you can understand (sorry if I have worded it really badly in the title)
See code below :D
names = ("Donald Trump James Barack Obama Sammy John Harry Potter")
# the names with surnames are the famous ones
# names without are regular names
list = names.split()
# I want to separate them into a list of separate names so I use split()
# but now surnames like "Trump" are counted as a name
print("Names are:",list)
This outputs
['Donald', 'Trump', 'James', 'Barack', 'Obama', 'Sammy', 'John', 'Harry', 'Potter']
I would like it to output something like ['Donald Trump', 'James', 'Barack Obama', 'Sammy', 'John', 'Harry Potter']
Any help would be appreciated
As said in the comments, you need a list of famous names.
# complete list of famous people
US_PRESIDENTS = (('Donald', 'Trump'), ('Barack', 'Obama'), ('Harry', 'Potter'))
def splitfamous(namestring):
words = namestring.split()
# create all tuples of 2 adjacent words and compare them to US_PRESIDENTS
for i, name in enumerate(zip(words, words[1:])):
if name in US_PRESIDENTS:
words[i] = ' '.join(name)
words[i+1] = None
# remove empty fields and return the result
return list(filter(None, words))
names = "Donald Trump James Barack Obama Sammy John Harry Potter"
print(splitfamous(names))
The resulting list:
['Donald Trump', 'James', 'Barack Obama', 'Sammy', 'John', 'Harry Potter']
String Split
Description
Split the string input_str = 'Kumar_Ravi_003' to the person's second name, first name and unique customer code. In this example, second_name= 'Kumar', first_name= 'Ravi', customer_code = '003'.
A sample output of the input 'Kumar_Ravi_003' is:
Ravi
Kumar
003
That is a what I try to do but I don't understand how to split it and store individual parts in different variables.
input_str = 'Kumar_Ravi_003'
second_name, first_name, customer_code = input_str.split("_")
input_str ='Kumar_Ravi_003'
name = input_str.split('_')
first_name=name[0]
second_name = name[1]
customer_code = name[2]
print(second_name +" "+ first_name+" "+customer_code)
Using:
cur.execute(SQL)
response= cur.fetchall() //response is a LOB object
names = response[0][0].read()
i have following SQL response as String names:
'Mike':'Mike'
'John':'John'
'Mike/B':'Mike/B'
As you can see it comes formatted. It is actualy formatted like:\\'Mike\\':\\'Mike\\'\n\\'John\\'... and so on
in order to check if for example Mike is inside list at least one time (i don't care how many times but at least one time)
I would like to have something like that:
l = ['Mike', 'Mike', 'John', 'John', 'Mike/B', 'Mike/B'],
so i could simply iterate over the list and ask
for name in l:
'Mike' == name:
do something
Any Ideas how i could do that?
Many thanks
Edit:
When i do:
list = names.split()
I receive the list which is nearly how i want it, but the elements inside look still like this!!!:
list = ['\\'Mike\\':\\'Mike\\", ...]
names = ['\\'Mike\\':\\'Mike\\", ...]
for name in names:
if "Mike" in name:
print "Mike is here"
The \\' business is caused by mysql escaping the '
if you have a list of names try this:
my_names = ["Tom", "Dick", "Harry"]
names = ['\\'Mike\\':\\'Mike\\", ...]
for name in names:
for my_name in my_names:
if myname in name:
print myname, " is here"
import re
pattern = re.compile(r"[\n\\:']+")
list_of_names = pattern.split(names)
# ['', 'Mike', 'Mike', 'John', 'John', 'Mike/B', '']
# Quick-tip: Try not to name a list with "list" as "list" is a built-in
You can keep your results this way or do a final cleanup to remove empty strings
clean_list = list(filter(lambda x: x!='', list_of_names))
I have two lists of sports players. One is structured simply:
['Lastname, Firstname', 'Lastname2, Firstname2'..]
The second is a list of lists structured:
[['Firstname Lastname', 'Team', 'Position', 'Ranking']...]
I ultimately want to search the contents of the second list and pull the info if there is a matching name from the first list.
I need to swap 'Lastname, Firstname' to 'Firstname Lastname' to match list 2's formatting for simplification.
Any help would be great. Thanks!
You can swap the order in the list of names with:
[" ".join(n.split(", ")[::-1]) for n in namelist]
An explanation: this is a list comprehension that does something to each item. Here are a few intermediate versions and what they would return:
namelist = ["Robinson, David", "Roberts, Tim"]
# split each item into a list, around the commas:
[n.split(", ") for n in namelist]
# [['Robinson', 'David'], ['Roberts', 'Tim']]
# reverse the split up list:
[n.split(", ")[::-1] for n in namelist]
# [['David', 'Robinson'], ['Tim', 'Roberts']]
# join it back together with a space:
[" ".join(n.split(", ")[::-1]) for n in namelist]
# ['David Robinson', 'Tim Roberts']