UPDATE : I have corrected my code and below is working fine as expected
Basically i need an output like below in mail.
I achieved this. but need to know if any efficient code then below one.
name 5001 5010 9000 4 %
name 5002 5010 9000 4 %
name 5003 5010 9000 4 %
name 5004 5010 9000 4 %
Storing the values in list.
Below are dummy values
container = []
for server in range(1,5):
container.append('name')
container.append(server + 5000)
container.append(5000+10)
container.append(4000+5000)
container.append(2500 % 12)
print('\n' + str(container))
Assign list of values to msgBody in order to send it via email
I'm just putting piece of code here. Below also working fine
msgBody1 = ''
for count in range(4):
if count == 0:
tempValue = '\n' + '\n' + str(container[count]) + '\t' + str(container[count+1]) + '\t' + str(container[count+2]) + '\t'
+ str(container[count+3]) + '\t' + str(container[count+4])
msgBody1 = msgBody1 + str(tempValue) + ' %'
elif count == 1:
tempValue = '\n' + '\n' + str(container[count+4]) + '\t' + str(container[count+5]) + '\t' + str(container[count+6]) + '\t'
+ str(container[count+7]) + '\t' + str(container[count+8])
msgBody1 = msgBody1 + str(tempValue) + ' %'
elif count == 2:
tempValue = '\n' + '\n' + str(container[count+8]) + '\t' + str(container[count+9]) + '\t' + str(container[count+10]) + '\t'
+ str(container[count+11]) + '\t' + str(container[count+12])
msgBody1 = msgBody1 + str(tempValue) + ' %'
elif count == 3:
tempValue = '\n' + '\n' + str(container[count+12]) + '\t' + str(container[count+13]) + '\t' + str(container[count+14]) + '\t'
+ str(container[count+15]) + '\t' + str(container[count+16])
msgBody1 = msgBody1 + str(tempValue) + ' %'
Any other better and short code to replace msgBody1
Thanks in advance
Your question is not clear; the code example does not make any sense. But from the structure of it, it seems like you are trying to use dict, but you are defining or sourcing lists.
Not sure why for server in servers, I hope your servers list is collection of numerical value, which does not make any sense.
Please go through list Vs dict, and list.append() and how to add new key, value pairs to dictionary.
Related
This question already has answers here:
Why do I get an IndexError (or TypeError, or just wrong results) from "ar[i]" inside "for i in ar"?
(4 answers)
Closed 6 months ago.
I am having trouble figuring out what is wrong with my code. I need help.
next(fhr) # skip header row
customer_list = [] # initialize empty customer list
for line in fhr:
ls = line.split(',')
customer_list.append([ls[0], ls[1], ls[2], ls[3], ls[4], ls[5], ls[6], int(ls[7]), ls[8], ls[9], ls[10].strip('\n')])
from operator import itemgetter
customer_list.sort(key=itemgetter(7), reverse=True)
print(customer_list)
writepath = './loan-data-output-v1.csv'
fwh = open(writepath, 'w', encoding='utf-8')
fwh.write('Name' +','+ 'State' +','+'Age' +','+'Annual Income'+','+ 'Loan Type' +','+' Loan Amount' +','+ 'Length of Loan in Years' +','+ 'Days Delinquent' +','+ 'Interest Rate' +','+ 'Number of Loans Prior' +','+'Years as Customer' + '\n')
for i in customer_list:
if customer_list[i][7] >= 90:
fwh.write(customer_list[i][0] + ',' + customer_list[i][1] + ',' + customer_list[i][2] + ',' + customer_list[i][3] + ',' + customer_list[i][4] + ',' + customer_list[i][5] + ',' + customer_list[i][6] + ',' + customer_list[i][7] + ',' + customer_list[i][8] + ',' + customer_list[i][9] + ','+ customer_list[i][10] + '\n')
fhr.close()
fwh.close()
I am getting this error for the last for loop and I'm not sure what to do about it. Can someone help.
TypeError: list indices must be integers or slices, not list
You are using lists of lists so when you use for i in list_of_list, i itself becomes a list..
for i in customer_list:
if i[7] >= '90':
fwh.write(i[0] + ',' + i[1] + ',' + i[2] + ',' + i[3] + ',' + i[4] + ',' + i[5] + ',' + i[6] + ',' + str(i[7]) + ',' + i[8] + ',' + i[9] + ','+ i[10] + '\n')
fhr.close()
fwh.close()
Alternatively you can use,
for i in range(0,len(customer_list)):
if customer_list[i][7] >= '90':
fwh.write(customer_list[i][0] + ',' + customer_list[i][1] + ',' + customer_list[i][2] + ',' + customer_list[i][3] + ',' + customer_list[i][4] + ',' + customer_list[i][5] + ',' + customer_list[i][6] + ',' + str(customer_list[i][7]) + ',' + customer_list[i][8] + ',' + customer_list[i][9] + ','+ customer_list[i][10] + '\n')
fhr.close()
fwh.close()
EDIT: Second method assumes that your length of customer_list is constant or in other words you are not adding anything to customer_list during the loop. Thanks to DanielRoseman for pointing out potential bug in second code..
EDIT 2:
Thanks to quamrana for suggesting this way,
for i in customer_list:
if i[7] >= '90':
i[7] = str(i[7])
fwh.write(','.join(i[0:11]) + '\n')
fhr.close()
fwh.close()
I'm trying to print a simple game board.
places = [" "] * 9
board = (places[8] + "|" + places[7] + "|" + places[6] + "\n",
places[5] + "|" + places[4] + "|" + places[3] + "\n",
places[2] + "|" + places[1] + "|" + places[0] + "\n")
print(board)
But instead of a board I get this:
(' | | \n', ' | | \n', ' | | \n')
I want to print it without the parentheses and with new lines instead of \n. How can I do this?
Don't print whole tuple, but it's elements, e.g.:
for i in board:
print(i)
You just have to use this line to print:
print(*board,sep="")
Explanation: the operator * is the unpacking operator: the tuple board is then unpacked, and it is like you've done:
print( places[8] + "|" + places[7] + "|" + places[6] + "\n",
places[5] + "|" + places[4] + "|" + places[3] + "\n",
places[2] + "|" + places[1] + "|" + places[0] + "\n",
sep="")
Because you've put commas on the end of each line in the brackets, you've made a tuple, which is an iterable, like a list. Just replace the commas with a + at the start of the next line
board = ('line 1' + '\n'
+ 'line 2' + '\n'
+ 'line 3' + '\n')
This creates a string instead of a tuple.
places = [" "] * 9
print(places[8] + "|" + places[7] + "|" + places[6] + "\n" + places[5] + "|" +
places[4] + "|" + places[3] + "\n" + places[2] + "|" + places[1] + "|" + places[0] +
"\n")
This is what you're looking for.
The problem was that "\n" only works in print statements.
i want to run a python file file.py 20 times with 1000 iterations with single run click so that i dont need to click run 20 times manually.
Init()
globalBest=pop[0].chromosome
# Saving Result
fp=open(resultFileName,"w");
fp.write("Iteration,Fitness,Chromosomes\n")
for i in range(0,iterations):
Crossover()
Mutation()
MemoriseGlobalBest()
if funEval >=maxFunEval:
break
if i%20==0:
print "I:",i,"\t Fitness:", bestFitness
fp.write(str(i) + "," + str(bestFitness) + "," + str(bestChromosome) + "\n")
print "I:",i+1,"\t Fitness:", bestFitness
fp.write(str(i+1) + "," + str(bestFitness) + "," + str(bestChromosome))
fp.close()
You can write another script which call your script 20 times. Make a loop and call the file.py 20 times in it.
try:
for iteration in range(20):
Init()
globalBest = pop[0].chromosome
# Saving Result
fp = open(resultFileName, "a")
fp.write("Iteration,Fitness,Chromosomes\n")
for i in range(0, iterations):
Crossover()
Mutation()
MemoriseGlobalBest()
if funEval >= maxFunEval:
break
if i % 20 == 0:
print
"I:", i, "\t Fitness:", bestFitness
fp.write(str(i) + "," + str(bestFitness) + "," + str(bestChromosome) + "\n")
print
"I:", i + 1, "\t Fitness:", bestFitness
fp.write(str(i + 1) + "," + str(bestFitness) + "," + str(bestChromosome))
fp.close()
I am receiving the following error when running a script to parse contents of an XML file.
if iteration.findtext("Iteration_query-def") in ecdict:
KeyError: 'XLOC_000434'
I was under the impression that using "if in dict" would mean that if the key is not found in the dictionary, the script will continue past the if statement and proceed with the rest of the code. Below is the problematic section of the code I am using. I realise this is quite a basic question, but I am unsure what else I can say, and I don't understand why I am receiving this error.
import xml.etree.ElementTree as ET
tree = ET.parse('507.FINAL_14.2.14_2_nr.out_fmt5.out')
blast_iteration = tree.find("BlastOutput_iterations")
for iteration in blast_iteration.findall("Iteration"):
query = iteration.findtext("Iteration_query-def").strip().strip("\n")
if query in score:
continue
if iteration.findtext("Iteration_message") == "No hits found":
if iteration.findtext("Iteration_query-def") in tair:
tairid = tair[iteration.findtext("Iteration_query-def")][0]
tairdes = tair[iteration.findtext("Iteration_query-def")][1]
else:
tairid = "-"
tairdes = "-"
goterms = ""
ecterms = ""
if iteration.findtext("Iteration_query-def") in godict:
for x in godict[iteration.findtext("Iteration_query-def")][:-1]:
goterms = goterms + x + ";"
goterms = goterms + godict[iteration.findtext("Iteration_query-def")][-1]
else:
goterms = "-"
if iteration.findtext("Iteration_query-def") in ecdict:
for x in ecdict[iteration.findtext("Iteration_query-def")][:-1]:
ecterms = ecterms + x + ";"
ecterms = ecterms + ecdict[iteration.findtext("Iteration_query-def")][-1]
else:
ecterms = "-"
if iteration.findtext("Iteration_query-def") in godescr:
desc = godescr[iteration.findtext("Iteration_query-def")]
else:
desc = "-"
n += 1
p = "PvOAK_up"+str(n) + "\t" + tranlen[iteration.findtext("Iteration_query-def")] + "\t" + orflen[iteration.findtext("Iteration_query-def")] + "\t" + "-" + "\t" + "-" + "\t" + tairid + "\t" + tairdes + "\t" + goterms + "\t" + ecterms + "\t" + desc + "\t" + str(flower[query][2]) + "\t" + str('{0:.2e}'.format(float(flower[query][1]))) + "\t" + str('{0:.2f}'.format(float(flower[query][0]))) + "\t" + str('{0:.2f}'.format(float(leaf[query][2]))) + "\t" + str('{0:.2f}'.format(float(leaf[query][1]))) + "\t" + str('{0:.2f}'.format(float(leaf[query][0])))
print p
Hope you can help,
Thanks.
edit: I should say that godict and ecdict were previously created as follows - I can submit the entire code if needs be:
godict = {}
ecdict = {}
godescr = {}
f = open("507.FINAL_14.2.14_2_nr.out_fmt5.out.annot")
for line in f:
line = line.split("\t")
if len(line) > 2:
godescr[line[0]] = line[2]
line[1] = line[1].strip("\n")
if line[1].startswith("EC"):
if line[0] in ecdict:
a = ecdict[line[0]]
a.append(line[1])
ecdict[line[0]] = a
else:
ecdict[line[0]] = [line[1]]
else:
if line[0] in godict:
a = godict[line[0]]
a.append(line[1])
godict[line[0]] = a
else:
godict[line[0]] = [line[1]]
Traceback:
Traceback (most recent call last):
File "2d.test.py", line 170, in <module>
p = "PvOAK_up"+str(n) + "\t" + tranlen[iteration.findtext("Iteration_query-def")] + "\t" + orflen[iteration.findtext("Iteration_query-def")] + "\t" + "-" + "\t" + "-" + "\t" + tairid + "\t" + tairdes + "\t" + goterms + "\t" + ecterms + "\t" + desc + "\t" + str(flower[query][2]) + "\t" + str('{0:.2e}'.format(float(flower[query][1]))) + "\t" + str('{0:.2f}'.format(float(flower[query][0]))) + "\t" + str('{0:.2f}'.format(float(leaf[query][2]))) + "\t" + str('{0:.2f}'.format(float(leaf[query][1]))) + "\t" + str('{0:.2f}'.format(float(leaf[query][0])))
KeyError: 'XLOC_000434'
else:
fullName = curLineFin[1] + ' ' + curLineFin[2]
players[fullName] = curLineFin[0] + '\t' + curLineFin[1] + \
'\t' + curLineFin[2] + '\t' + curLineFin[3] + '\t' + \
curLineFin[4] + '\t' + curLineFin[5] + '\t' + curLineFin[6] + \
'\t' + curLineFin[7] + '\t' + curLineFin[8] + '\t' + \
curLineFin[9] + '\t' + curLineFin[10] + '\t'
Every time I run the script, I get the error:
players[fullName] = curLineFin[0] + '\t' + curLineFin[1] + \
^
IndentationError: unindent does not match any outer indentation level
Wrap your code with parentheses
players[fullName] = (curLineFin[0] + '\t' + curLineFin[1] +
'\t' + curLineFin[2] + '\t' + curLineFin[3] + '\t' +
curLineFin[4] + '\t' + curLineFin[5] + '\t' + curLineFin[6] +
'\t' + curLineFin[7] + '\t' + curLineFin[8] + '\t' +
curLineFin[9] + '\t' + curLineFin[10] + '\t' )
or
players[fullName] = '\t'.join(curLineFin[:11]) + '\t'
or if this trailing tab char is not needed and you have exactly eleven elements in curLineFin.
players[fullName] = '\t'.join(curLineFin)
Just use parenthesis:
fullName = (curLineFin[1] + ' ' + curLineFin[2] +
players[fullName] = curLineFin[0] + '\t' + curLineFin[1] +
'\t' + curLineFin[2] + '\t' + curLineFin[3] + '\t' +
curLineFin[4] + '\t' + curLineFin[5] + '\t' + curLineFin[6] +
'\t' + curLineFin[7] + '\t' + curLineFin[8] + '\t' +
curLineFin[9] + '\t' + curLineFin[10] + '\t')
The code you have posted does not generate that error, so it's impossible to diagnose exactly what's happening in the different code you're actually running.
The most likely cause is that it's completely unrelated to the backslashes, and you're doing something like mixing tabs and spaces. (The fact that you're using a weird 6-character indent for the block isn't a good sign…)
Another possibility is that you're putting extra spaces after one of the backslashes. This should usually give you a SyntaxError: unexpected character after line continuation character, but it's possible to confuse Python to the point where that passes and you get the following generic SyntaxError for a + with no right operand or IndentationError for the next line.