Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a variable called message.
that variable has value like below:
:1A:name
:1B:Address
:1C:phone
:2A:/256789422254
TEST VALUE
:2B:/INSTITUTION
from above variable I want to take only :2A: field contains value
which means I wants only below two line
:2A:/256789422254
TEST VALUE
I tried with
lines = message.readlines()
for index,line in enumerate(lines):
if :2A: in line:
print lines [index+2]
which is not working.
Try this:
s = '''
:1A:name
:1B:Address
:1C:phone
:2A:/256789422254
TEST VALUE
:2B:/INSTITUTION
'''
x, y = s[s.index(':2A:') - 1 :].strip().split("\n")[:2]
x = x.split(':')[2]
print(x, y)
Output:
/256789422254 TEST VALUE
message=""":1A:name
:1B:Address
:1C:phone
:2A:/256789422254
TEST VALUE
:2B:/INSTITUTION"""
def solver(lines):
x, y = 0, 0
for i, line in enumerate(lines):
if line.find(':2A:') == 0:
x = i
if line.find(':2B:') == 0:
y = i
break
return lines[x:min(x + 2, y)]
solver(message.split('\n'))
#Output [':2A:/256789422254', 'TEST VALUE']
The solution works by finding the index of ':2A' in the array of lines. It also finds the position of ':2B' in the array. Then it merely returns a slice of the lines in between.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
The program runs and the function works but I am not able to see my docCountryList in the output. Can someone tell me why?
I have this code
def ViewByCountry(docID,user_selection):
docCountryList=[]
for x in jfile:
if x.get('subject_doc_id') == docID:
docCountryList.append(x['visitor_country'])
if user_selection == '2a':
x = []
y = []
#Insert countries and number of occurences in two seperate lists
for k,v in Counter(docCountryList).items():
x.append(k)
y.append(v)
plt.title('Countries of Viewers')
plt.bar(range(len(y)), y, align='center')
plt.xticks(range(len(y)), x, size='small')
plt.show()
return docCountryList
and in my main
from program import ViewByCountry
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
docID = input("Enter required document ID: ")
user_selection = input("Enter selection")
ViewByCountry(docID,user_selection)
You never print out the value of docCountryList, so try this:
print(ViewByCountry(docID,user_selection))
This will print out the value.
You can do this as well:
lst = ViewByCountry(docID,user_selection)
print(lst)
In your main you can change to myView = ViewByCountry(docID,user_selection) and then add print(myView). This saves the list created by your function to a variable to be printed or used later.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
This post was edited and submitted for review 4 days ago.
Improve this question
def _init_(self. row, col, data):
self.child = {}
self.row = row
self.col = col
self.data = data
self.active = True
file = open('filename.txt', 'r')
maze = file.readlines()
n = (intmaze[0])
full = maze[1:(n*n)+1]
file.close
Value error: invalid literal for int() with base 10:'2,1,1,3\n'
I am trying to read a text file with the following matrix
2,1,1,3
2,1,2,3
1,1,2,3
3,G,3,1
You have replace n = int(maze[0]) with the following ->
You have to first store it into list by l = maze.split(",") then you can write n = len(l) to get the length of the matrix.
with open("maze.txt","r") as fd:
maze = [i.split(",") for i in fd.read().splitlines()]
print(len(maze[0]))
print(maze)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Why am I getting this error?
motModel = motordata.get('displayAttributes')[1]['value'] or None
IndexError: list index out of range
I'm scraping car listings and for this particular list there is only 1 item on the list.
In other words motordata.get('displayAttributes')[0] is there but motordata.get('displayAttributes')[1] is not there.
I thought that by using i in range(len(my_list)) it would return a value if the key existed and move on to the next key/item if it didn't.
my_list = motordata['displayAttributes']
for i in range(len(my_list)):
motMake = motordata.get('displayAttributes')[0]['value'] or None
motModel = motordata.get('displayAttributes')[1]['value'] or None
motYear = motordata.get('displayAttributes')[2]['value'] or None
motMilage = motordata.get('displayAttributes')[3]['value'] or None
motFuel = motordata.get('displayAttributes')[4]['value'] or None
This loop is indeed not exceeding the range of the list:
for i in range(len(my_list)):
Within that loop, you can access list elements using i as the index safely. But that's not what you're doing, you're using hard-coded index values:
motMake = motordata.get('displayAttributes')[0]['value'] or None
motModel = motordata.get('displayAttributes')[1]['value'] or None
motYear = motordata.get('displayAttributes')[2]['value'] or None
motMilage = motordata.get('displayAttributes')[3]['value'] or None
motFuel = motordata.get('displayAttributes')[4]['value'] or None
So "for each item in the list" you're telling the code to "give me the first 5 items". You're explicitly telling the code to access the second item in a list that you know has only one item. So, you get an exception.
It looks like you don't want a loop at all, since you're never actually using i and always over-writing the same variables in the loop. Instead, check the length of the list before accessing each of the 5 hard-coded index values. Something like this:
my_list = motordata['displayAttributes']
length = len(my_list)
if length > 0:
motMake = motordata.get('displayAttributes')[0]['value']
if length > 1:
motModel = motordata.get('displayAttributes')[1]['value']
if length > 2:
motYear = motordata.get('displayAttributes')[2]['value']
if length > 3:
motMilage = motordata.get('displayAttributes')[3]['value']
if length > 4:
motFuel = motordata.get('displayAttributes')[4]['value']
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am getting an invalid syntax error
SyntaxError: invalid syntax
root#collabnet:/home/projects/twitterBot# python twitterBot2.py
File "twitterBot2.py", line 58
return screenNames
when returning a dictionary from this function:
def getUserName(lookupIds):
l = len(lookupIds) # length of list to process
i = 0 #setting up increment for while loop
screenNames = {}#output dictionary
count = 0 #count of total numbers processed
print 'fetching usernames'
while i < l:
toGet = []
toAppend = []
if l - count > 100:#blocks off in chunks of 100
for m in range (0,100):
toGet.append(lookupIds[count])
count = count + 1
print toGet
else:#handles the remainder
print 'last run'
r = l - count
print screenNames
for k in range (0,r):#takes the remainder of the numbers
toGet.append(lookupIds[count])
count = count + 1
i = l # kills loop
toAppend = api.lookup_users(user_ids=toGet)
print toAppend
screenNames.append(zip(toGet, toAppend)
#creates a dictionary screenNames{user_Ids, screen_Names}
#This logic structure breaks up the list of numbers in chunks of 100 or their
#Remainder and addes them into a dictionary with their count number as the
#index value
#print str(len(toGet)), 'screen names correlated'
return screenNames
I am running the function like so:
toPrint = {}#Testing Only
print "users following", userid
toPrint = getUserName(followingids)#Testing Only
I have tried commenting out and just printing screenNamesand I still get the same error except on the print statement instead. I am pretty sure I am running the return right thanks for the look.
You forgot a closing parenthesis on a preceding line:
screenNames.append(zip(toGet, toAppend)
# ^ ^ ^^?
# | \---- closed ---/|
# \----- not closed ---/
You'll have another problem here, as screenNames is a dict object, not a list, and has no .append() method. If you wanted to update the dictionary with key-value pairs, use update() instead:
screenNames.update(zip(toGet, toAppend))
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
The code below reads lines from a file, then it executes the custom function (My_Function) and return values to the variables(e.g. condition_A)
for line in input_file:
if condition_A:
condition_A = My_Function(A_tuple[0], B_tuple[0])
if condition_B:
condition_B = My_Function(A_tuple[1], B_tuple[1])
if condition_C:
condition_C = My_Function(A_tuple[2], B_tuple[2])
if condition_D:
condition_D = My_Function(A_tuple[3], B_tuple[3])
if condition_E:
condition_E = My_Function(A_tuple[4], B_tuple[4])
...
My question is: can the code be modified to more elegant version? After all, many code is similar(I don't want to define another function to simplify it because the code is still similar after the new function is defined). thanks.
Instead of having 5 variables condition_*, use a list, conditions:
conditions=[1]*5 # initialize conditions as you wish
for line in input_file:
for i,condition in enumerate(conditions):
if condition:
conditions[i]=My_Function(A_tuple[i],B_tuple[i])
What about something like
conditions = [condition_A, condition_B, condition_C, condition_D, condition_E]
condition_test = lambda c, i: My_Function(A_tuple[i], B_tuple[i]) if c else c
for line in input_file:
conditions = [condition_test(c, i) for i, c in enumerate(conditions)]
'line' is not referenced in teh loop, is that an error in simplifying it for posting?
How about
condition=1 #or 2 or...
for line in input_file:
My_Function(A_tuple[condition],B_tuple[condition])
Before refactoring your code on a purely syntactic level (which is covered in examples above), it might be useful to evaluate what you're doing with the code on a functional level
Check out your condition_x variables. I think you might be using the same variable for two different things (both type-wise and logically) - usually a bad idea in a weakly typed language. It looks to me as if the user sets a condition to true or false, and then that condition is assigned the output - is the output boolean? is it related to the original value of that variable? Rethinking this might lead to more understandable code.
It is also difficult to evaluate how this can be refactored without seeing what goes in to condition_x - since these might have commonalities.
One more sample(not solution) based on unutbu's:
data = [1,2,3,'',4,5,6, '', 0]
for i in (i for i in xrange(len(data)) if data[i] not in ['',0]):
data[i] += 1
Sorry if duplicate
Here is a generic solution where you can have custom index and you can also access conditions by name if need be and it can be easily extended to add any new complexities
class Condition(object):
def __init__(self, active, index1, index2):
self.active = active
self.index1 = index1
self.index2 = index2
conditions = {
'A': Condition(True,0,0),
'B': Condition(True,1,1),
'C': Condition(True,2,2),
'D': Condition(True,3,3),
'E': Condition(True,4,4),
}
for line in input_file:
for condition in conditions.itervalues():
if condition.active:
condition.active = My_Function(A_tuple[condition.active.index1], B_tuple[condition.active.index2])