when I print "amount", I am getting duplicate values. Does this have to do with two for loops back to back on my first three lines?
missing_amount:
['102,131.49']
expected results:
102,131.49
actual results:
102,131.49
102,131.49
code:
body_l = []
for link in url:
body = browser.find_element_by_xpath("//[contains(text(), 'Total:')]").text
body_l.append(body)
icl_dollar_amount = re.findall('(?:[\£$\€]{1}[,\d]+.?\d)', body)[0].split('$', 1)[1]
icl_dollar_amount_l.append(icl_dollar_amount)
if not missing_amount:
logging.info("List is empty")
print("List is empty")
count = 0
for amount in missing_amount:
for count, item in enumerate(icl_dollar_amount_l):
if amount == item:
body = body_l[count]
get_company_id = body.split("Customer Id:", 1)[1][4:10].strip()
else:
amount_ack_missing_l.append(amount)
logging.info("Missing " + str(amount))
print("Missing " + str(amount))
With AgentJRock code:
when I print(icl_dollar_amount[i]) and missing_amount[i] my if statement never runs only the else runs. But both list have the same values, please see below.
for i in range(len(missing_amount)):
print("Missing Amount : ", missing_amount[i])
print("ICL DOLLAR", icl_dollar_amount_l[i])
if missing_amount[i] == icl_dollar_amount_l[i]:
body = body_l[i]
get_company_id = body.split("Customer Id:", 1)[1][4:10].strip()
else:
amount_ack_missing_l.append(missing_amount[i])
logging.info("Missing " + str(missing_amount[i]))
print("Missing " + str(missing_amount[i]))
print(icl_dollar_amount[i]
ICL DOLLAR 2,760,127.58
ICL DOLLAR 325,845.84
print(missing_amount[i])
Missing Amount : 325,845.84
Missing Amount : 2,760,127.58
you do print("Missing " + str(amount)), but also logging.info("Missing " + str(amount)). I don't know what logging.info does, but i assume it prints to stdout. I'd recommend you to remove the print("Missing " + str(amount))
Yes, you are correct, the inner loop is getting your missing_amount twice.
What type/values are in missing amount, icl_dollar_amount_l, and body_l?
Going off missing values is a list of ints
and icl_dollar_amount_l is another list ints
and bod_l is a dictionary
you might be best doing a single for loop to create an index from a range of the length of your lists. From this index in the for loop, you can compare indexes between two lists of shared indices. I think you're trying to share this index with your dict, which should be no problem with the same index we created
also, You have a count variable outside the for loop but have set another instance of count to the enumerate variable.
the outside count needs to be used with a (+=/-+) set to that variable which is equivalent to the enumerate and redundant.
for i in range(len(missing_amount)):
if missing_amount[i] == icl_dollar_amount_l[i]:
body = body_l[i]
get_company_id = body.split("Customer Id:", 1)[1][4:10].strip()
else:
amount_ack_missing_l.append(missing_amount[i])
logging.info("Missing " + str(missing_amount[i]))
print("Missing " + str(missing_amount[i]))
Related
I am new to Python, and I am making a list. I want to make a print statement that says "Hello" to all the values in the lists all at once.
Objects=["Calculator", "Pencil", "Eraser"]
print("Hello " + Objects[0] + ", " + Objects[1] + ", " + Objects[2])
Above, I am repeating "Objects" and its index three times. Is there any way that I can simply write "Objects" followed by the positions of the values once but still get all three values printed at the same time?
Thanks
You could use join() here:
Objects = ["Calculator", "Pencil", "Eraser"]
print('Hello ' + ', '.join(Objects))
This prints:
Hello Calculator, Pencil, Eraser
You can use the string join function, which will take a list and join all the elements up with a specified separator:
", ".join(['a', 'b', 'c']) # gives "a, b, c"
You should also start to prefer f-strings in Python as it makes you code more succinct and "cleaner" (IMNSHO):
Objects = ["Calculator", "Pencil", "Eraser"]
print(f"Hello {', '.join(Objects)}")
Not sure this is the most elegant way but it works:
strTemp = ""
for i in range(len(Objects)):
strTemp += Objects[i] + " "
print ("Hello " + strTemp)
Start with an empty string, put all the values in your list in that string and then just print a the string Hello with your Temporary String like above.
I wish to create a program in Python that prompts the user to enter a number of integer values. The
program stores the integers, counts the frequency of each integer and displays the frequency
as per the below image.
I have the following code but I don't know how to execute the final step (i.e. print "1 occurs 2 times" and below that "2 occurs 3 times" etc)
selection = int(input("Input the number of elements to be stored in the list: "))
counter = 1
valuesList = []
while counter <= selection:
value = input("Element - " + str(counter) + ": ")
valuesList.append(value)
counter +=1
#count number occurrences of each value
import collections
counter=collections.Counter(valuesList)
#create a list for the values occurring and a list for the corresponding frequencies
keys = counter.keys()
values2 = counter.values()
print("The frequency of all elements in the list: ")
Below the last print should be a series of print commands: keys[0] + "occurs" + values2[0] + "times" and continue for the all values within 'keys'. But I don't know how to print for all values in the list if the length of the list changes depending on the original 'selection' input.
Something like this is a compact solution for what you need using list comprehension and the count function of lists
print('The frequency of all elements of the list :')
print('\n'.join({f'{i} occurs {valuesList.count(i)} times' for i in valuesList}))
You can use itertools library. This should work for you.
import itertools
print("The frequency of all elements in the list: ")
for key, vals in itertools.zip_longest(keys, values2):
print("{0} occurs {1} times".format(key, vals))
I'm trying to get a substring in a for loop. For that I'm using this:
for peoject in subjects:
peoject_name = peoject.content
print(peoject_name, " : ", len(peoject_name), " : ", len(peoject_name.split('-')[1]))
I have some projects that don't have any "-" in the sentence. How can I deal with this?
I'm getting this issue:
builtins.IndexError: list index out of range
for peoject in subjects:
try:
peoject_name = peoject.content
print(peoject_name, " : ", len(peoject_name), " : ", len(peoject_name.split('-')[1]))
except IndexError:
print("this line doesn't have a -")
you could just check if there is a '-' in peoject_name:
for peoject in subjects:
peoject_name = peoject.content
if '-' in peoject_name:
print(peoject_name, " : ", len(peoject_name), " : ",
len(peoject_name.split('-')[1]))
else:
# something else
You have a few options, depending on what you want to do in the case where there is no hyphen.
Either select the last item from the split via [-1], or use a ternary statement to apply alternative logic.
x = 'hello-test'
print(x.split('-')[1]) # test
print(x.split('-')[-1]) # test
y = 'hello'
print(y.split('-')[-1]) # hello
print(y.split('-')[1] if len(y.split('-'))>=2 else y) # hello
print(y.split('-')[1] if len(y.split('-'))>=2 else '') # [empty string]
i made var with input word , then the output of word is encode hex , but what i need is to made another var with number if the input are 10 , the output = 1,2,3,4,5,6,7,8,9,10 , then i need to join the word with each number .. so the output would be , hexedWord1,hexedWord2,hexedWord3 ... etc .. here is my code
num = raw_input("Inset the number of students. ")
for num in range(1, num + 1)
print num
word = raw_input("Insert the name of student to encrypt it to hex. ")
res = "0x" + word.encode('hex') + num
print res
It's a little hard to tell what you are asking, but from what I understand, you the encrypted student names separated by commas with their number following the name
There are a few errors with your code. For one, raw_input("Inset the number of students. ") returns a string, but you use it like an integer. To fix this, do num = int(raw_input("Inset the number of students. ")) There are further things you can do to keep the user from giving you something weird, but this will work.
Another problem is with res. For each student, res is being reset. You want the information to be added to it. This could easily be done with a += operator, but if you want them separated by commas, the best thing I can think of is using an array that can be joined together with commas later on.
All together, the code would look like this:
num = int(raw_input("Inset the number of students. "))
res = []
for num in range(1, num + 1):
print num
word = raw_input("Insert the name of student to encrypt it to hex. ")
res.append("0x" + word.encode('hex') + str(num))
print ",".join(res)
Personally, using num as both the iterator of the for loop as well as num feels weird, but I'll let you keep that.
First of all,
when you read input from user using raw_input the value is stored in "num" as string,
So range(1,num+1) throws an error.
So either use
num = input("Inset the number of students. ")
or
num = int(raw_input("Inset the number of students. "))
Secondly,
There is a missing colon(:) at the end of for
fix it like this:
for num in range(1, num + 1):
Thirdly, you are using the same variable "res" for storing the result of every stage, so it gets overwritten.
I prefer you use a list to store values
Declare a empty list before the for loop and append new result to it within the loop
Finally, this statement throws an error
res = "0x" + word.encode('hex') + num
Fix it by:
res = "0x" + word.encode('hex') + str(num)
What happened was that, you tried to concatenate 3 objects of different type using "+" which produces TypeError in Python
the Final code would be something like this:
num = input("Inset the number of students. ")
res = []
for num in range(1, num + 1):
print num
word = raw_input("Insert the name of student to encrypt it to hex. ")
res.append("0x" + word.encode('hex') + str(num))
for r in res:
print r
This should work (Assuming this is what you expect)
I am having issues with formatting and understand lists and strings when it comes to classes.
So I have this code here:
class User:
def __init__(self,title):
self.tile=tile
self.rank={}
def addCard(self,compID,number):
if compID in self.cards and number > self.cards[compID]:
self.cards[compID]=number
elif compID not in self.cards:
self.cards[compID]=number
def __str__(self):
self.cardList = []
for compID, number in self.cards.items():
final = compID + "-" + str(number)
self.cardList.append(temp)
self.cardList.sort()
return self.tile + ":" + " " + "Card scores:" + str(self.cardList)
so my result looks like this:
OUTPUT 1:
Cpt.Fred: Card scores: ['diamond-22', 'hearts-4', 'spades-3']
Lt.Connor: Card scores: ['diamond-43']
I am trying to make my result look like this:
OUTPUT 2:
Cpt.Fred: Card scores: [ diamond-22, hearts-4, spades-3 ]
Lt.Connor: Card scores: [ diamond-43 ]
The data is not whats important, its how to get rid of the " ' " at the beginning and the end of the results. I think it has something to do with my last def() statement but I have been trying to format it every way with no luck. Can anyone help turn the first output to look like the second output?
Instead of calling str(self.cardList), you should do:
return "%s: Card scores: [%s]" % (self.title, ", ".join(self.cardList))
The problem is that str on a list calls repr (includes quotes) on the list's elements, whereas you just want the str of the elements joined by commas.
You may need to process and print the list manually. Here's one way you could do that.
def printList(cardlist):
printstr = "[" # Start with [.
for card in cardlist:
printstr += card + ", " "card, "
printstr = printstr[:-2] + "]" # Remove the last ", " before adding the last ].
The problem is in "str(self.cardList)". It prints out the list as is, meaning it puts strings into quotations to distinguished them from numbers and other objects.
def list_to_string(some_list):
str = "["
for i in range(len(some_list)):
str += some_list[i]
if i < len(some_list)-1:
str += ", "
str += "]"
return str
this would parse your list into a string without the quotations