beatles = []
print(beatles)
beatles.append("John Lennon")
beatles.append("Paul McCartney")
beatles.append("George Harrison")
print(beatles)'
for i in range(len(beatles):
beatles.append("Stu Sutcliffe")
beatles.append("Pete Best")
Need help with the for loop using append()
I'm Honestly not too sure what your asking for but to my understanding your looking for a way to add to a list using input then try this out for size.
You can replace list() with [] if you desire
beatles = list()
while True:
inp = input("Add Name to list ")
if inp == 'done' : break
beatles.append(inp)
beatles.append("John Lennon")
beatles.append("Paul McCartney")
beatles.append("George Harrison")
print(beatles)
Related
So the problem I have is I think that the code is good, but it doesn't work as I would like it to.
Make a program that filters a list of strings and returns a list with only your friends name in it.
If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he's not...
Ex: Input = ["Ryan", "Kieran", "Jason", "Yous"], Output = ["Ryan", "Yous"]
The code I wrote:
def friend(x):
for x in friend:
split_words = x.split( )
word_count = len(split_words):
if word_count = 4:
print(x)
Thanks in advance!
Iterate over the list of names.
Check each name's length: Using the helper function is_friend.
Collect the name if it is a friend in a list.
Print the resulting list.
Input = ["Ryan", "Kieran", "Jason", "Yous"]
def is_friend(name):
return len(name) == 4
friends = []
for name in Input:
if is_friend(name):
friends.append(name)
print(friends)
Or a shorter version using list comprehension:
friends = [name for name in Input if len(name) == 4]
print(friends)
I hope that you're doing well.
I'm kinda blocked on one part of my project. This a finance oriented project.
Basically, what I want is to loop through a dictionary of financial characteristics such as this:
indices={'Revenues':revenue,'Cost Of Revenues':COGS,'Selling General & Admin Expenses':SGA,
'R&D Expenses':RD,'Operating Income':OperatingIncome}
During my for loop, I wish to have just one line rather than doing this:
if count==1:
prediction_revenue=finalpred
elif count==2:
prediction_COGS=finalpred
elif count==3:
prediction_SGA=finalpred
elif count==4:
prediction_RDA=finalpred
else:
prediction_operatingincome=finalpred[[key,'Date']]
Do you know how I could do that? That would greatly help me.
It's never a good idea to generate variables. Proper pythonic way of doing this is to use a dictionary:
prediction = {}
if count==1:
prediction['revenue'] = finalpred
elif count==2:
prediction['COGS'] = finalpred
elif count==3:
prediction['SGA'] = finalpred
elif count==4:
prediction['RDA'] = finalpred
else:
prediction['operatingincome'] = finalpred[[key,'Date']]
Not sure if this is what you are looking for, but you can access dictionary values through it's keys.
prediction['revenue'] = finalpred
prediction['COGS'] = finalpred
prediction['SGA'] = finalpred
prediction['RDA'] = finalpred
prediction['operatingincome'] = finalpred[[key,'Date']]
If your intention is to just assign finalpred to any key in your dictionary that's easy:
for prediction_name, prediction_value in indices:
prediction_value = finalpred
You can iterate any dictionary like in the example above.
I have a file that I have to read. In every line, there is a name, age, height, and weight. There are a lot of lines in the file and I only need the names. Here is my code:
import random
import string
dictionary = {}
lst = []
with open("persons.dat","r") as file:
for line in file:
items = line.split(',') #this makes this ['Bill Johnson', '31', '196', '93']
key = items[0]
dictionary[key] = []
for i in range(1,len(items)):
dictionary[key].append(int(items[i]))
#print(dictionary)
for key in dictionary.keys():
lst.append(key)
print(lst)
def generateGroup(sizeOfGroup):
for names in range(sizeOfGroup):
random_names = random.choice(lst)
print(random_names)
My code gets all of the names in the list as intended. The code works fine up to generateGroup()
I need a function that would ask for the size of a group (some number) of the list and give random names from that list.
I don't know how to implement that function. I kind of get the logic of the function, but I don't know where I should put the function in the code (like which line).
random.sample does exactly this.
def generateGroup(sizeOfGroup):
print(random.sample(lst, k=sizeOfGroup))
random.sample returns a list. You could accumulate the list yourself
random_names = []
for names in range(sizeOfGroup):
random_names.append(random.choice(lst))
print(random_names)
but random.sample ensures that you won't select the same name twice.
Once generateGroup is defined correctly, you still need to call it with an argument:
while True:
try:
n = int(input("Enter a number: "))
break
except ValueError:
print("That's not an integer, try again")
generateGroup(n)
I am working pyhton on codecademy and I stucked in one part. The goal is this: "Define a function called reverse that takes a string 'text' and returns that string in reverse. You may not use reversed or [::-1] to help you with this."
I did this one and it is not working like this:
t = raw_input("Enter: ")
def reverse(t):
x = []
for a in range(len(t)):
x.append(t[len(t) - a - 1])
print ''.join(x)
but when I do it like this it is working.
t = raw_input("Enter: ")
x = []
for a in range(len(t)):
x.append(t[len(t) - a - 1])
print ''.join(x)
what is wrong with the first one?
The first does not work because, you're not calling your reverse function on t.
def reverse(t):
x = []
for a in range(len(t)):
x.append(t[len(t)-a-1])
return ''.join(x)
t = raw_input("Enter: ")
print(reverse(t))
In your example you're obtaining the input, but doing nothing with it.
I've got a loop that is supposed to select features and keep looping until it is no longer selecting new features
arcpy.SelectLayerByLocation_management("antiRivStart","INTERSECT","polygon")
previousselectcount = -1
selectcount = arcpy.GetCount_management("StreamT_StreamO1")
while True:
#selectCount = arcpy.GetCount_management("StreamT_StreamO1")
mylist = []
with arcpy.da.SearchCursor("antiRivStart","ORIG_FID") as mycursor:
for feat in mycursor:
mylist.append(feat[0])
liststring = str(mylist)
queryIn1 = liststring.replace('[','(')
queryIn2 = queryIn1.replace(']',')')
arcpy.SelectLayerByAttribute_management('StreamT_StreamO1',"ADD_TO_SELECTION",'OBJECTID IN '+ queryIn2 )
arcpy.SelectLayerByLocation_management("antiRivStart","INTERSECT","StreamT_StreamO1","","ADD_TO_SELECTION")
previousselectcount = selectcount
selectcount = arcpy.GetCount_management("StreamT_StreamO1")
print str(selectcount), str(previousselectcount)
if selectcount == previousselectcount:
break
By my reckoning, once it starts print the name number twice it should stop, but it doesn't, its keeps print "15548 15548" over and over again. Is it ingnoring the break or is the if condition not being met?
I've also tried with
while selectcount != previousselectcount:
but this gave me the same result
Variables in Python are dynamic. Just because you initialise previousselectcount as an integer doesn't mean it will be one when you call previousselectcount = selectcount. You can feel free to get rid of that line.
If you replace:
selectcount = arcpy.GetCount_management("StreamT_StreamO1")
With:
selectcount = int(arcpy.GetCount_management("StreamT_StreamO1").getOutput(0))
For both lines you'll be comparing the integer values instead of whatever the equality operator is comparing for the object.
Even better, why not write a function to do it for you:
def GetCount():
return int(arcpy.GetCount_management("StreamT_StreamO1").getOutput(0))
Save yourself repeating yourself.