I have a list with like this that goes from 0 to 1000 .
x = ['0_1','0_2','0_3' ..., '1000_1','1000_2','1000_3']
I need it to count every time the char in index changes like I show below.
list_leng = len(x)
for i in range(0, list_leng):
y = x[i]
z = y[0]
print this should iterate through all the list and only print when the z number changes ' # how should I make it print '
If I understood your question well, the answer must be something like this;
comparisonText = ""
for each in x:
preNumber = each.split('_')[0]
if comparisonText != preNumber:
print preNumber, 'is different than previous.'
comparisonText = preNumber #change the comparisonText
Related
I need to replace temperature values in list depends on negative/positive and get rid of float at the same time. I.e. value '-0.81' should be '-1' (round) or '0.88' should be '1'.
myList = ['-1.02', '-1.03', '-0.81', '-0.17', '-0.07', '0.22', '0.88', '0.88', '0.69']
for i in range (len(myList)):
if myList[i][0] == '-' and int(myList[i][-2]) > 5:
do sth...
At the end I need new list with new values. Thank you for any tips.
Your code is already almost there. It's not necessary to reference the elements by index.
myList = ['-1.02', '-1.03', '-0.81', '-0.17', '-0.07', '0.22', '0.88', '0.88', '0.69']
for i in myList:
if i[0] == '-' and int(i[-2]) > 5:
do sth...
If all you want to do is rounding then you can use a list comprehension.
roundlist = [round(float(i)) for i in myList]
You could parse the string into number, check for rounding (whether the decimal is higher or lower than 0.5), and convert it back to string
import math
myList = ['-1.02', '-1.03', '-0.81', '-0.17', '-0.07', '0.22', '0.88', '0.88', '0.69']
result = [0] * len(myList)
for i in range (len(myList)):
num = float(myList[i])
if num - math.floor(num) < 0.5:
result[i] = str(math.floor(num)) # round down
else:
result[i] = str(math.ceil(num)) # round up
print(result)
This is my first post in Stack Overflow. It's my pleasure to say hello to everyone, after all these years on being merely a lurker!
I am currently learning to code in my free time (specifically, Python). While developing my second project, I got stuck with a function that refuses to work as I intended. Since I can't find any documentation that helps me to find why, I decided to aske here. The code is the following:
def GridConstructor(InputGrid, RedPosition, BluePosition, SquareSize, StartingPositionA, StartingPositionB):
CurrentPositionA = StartingPositionA
CurrentPositionB = StartingPositionB
x = 1
for Line in range(19):
y = 1
for Row in range(18):
if [y, x] == BluePosition:
InputGrid[str(x) + ", " + str(y)] = [CurrentPositionA, CurrentPositionB], 1
print CurrentPositionA, CurrentPositionB
elif [y, x] == RedPosition:
InputGrid[str(x) + ", " + str(y)] = [CurrentPositionA, CurrentPositionB], 2
print CurrentPositionA, CurrentPositionB
else:
InputGrid[str(x) + ", " + str(y)] = [CurrentPositionA, CurrentPositionB], 0
print CurrentPositionA, CurrentPositionB
y += 1
CurrentPositionA[1] += SquareSize
CurrentPositionB[1] += SquareSize
x += 1
CurrentPositionA[0] += SquareSize
print CurrentPositionA[0]
CurrentPositionB[0] += SquareSize
print CurrentPositionB[0]
CurrentPositionA[1] = StartingPositionA[1]
print CurrentPositionA[1]
print StartingPositionA[1]
CurrentPositionB[1] = StartingPositionB[1]
print CurrentPositionB[1]
print StartingPositionB[1]
(feel free to ignore the 'print', they're there for debugging purposes).
As you can see it's a pretty simple function to create a dictionary storing [x, y] coordinates in a grid pattern. Judging by the debugging, the problem seems to be that at the moment of adding 'SquareSize' to 'CurrentPositionA' and 'CurrentPositionB' in the second 'for' loop, the value of 'SquareSize' is for some reason added to 'StartingPositionA' and 'StartingPositionB', which means that the y value of both current position trackers do not reset to its original value at the end of each iteration of the first for loop. I have absolutely no idea why the function is doing that, and I can't find any documentation that can help me. I'm sure it is some very stupid, elementary error in action, but I'd be very grateful if someone can help me with this.
Cheers!
The issue is occurring because of these two assignment statements.
CurrentPositionA = StartingPositionA
CurrentPositionB = StartingPositionB
Let me explain the problem
list1 = [1,2]
list2 = list1
list1[1] = 3
print(list1)
print (list2)
print (id(list1))
print (id(list2))
output:-
[1, 3]
[1, 3]
139674729442312
139674729442312
This occurs because list1,list2 variables point to same memory location, there by changing content in one variable changes content in other variable
which is not what you expected.
To avoid this problem you need to deepcopy your objects rather than just assignment.
import copy
list1 = [1,2]
list2 = copy.deepcopy(list1)
list1[1] = 3
print(list1)
print (list2)
print (id(list1))
print (id(list2))
output:-
[1, 3]
[1, 2]
139997249899528
139997259457928
basically replace CurrentPositionA, CurrentPositionB assignments with below commands and see it it works(after importing copy).
CurrentPositionA = copy.deepcoy(StartingPositionA)
CurrentPositionB = copy.deepcopy(StartingPositionB)
I am attempting to analyze data sets as lists of differing lengths. I am calling lines (rows) of my data set one by one to be analyzed by my function. I want the function to still be run properly regardless of the length of the list.
My Code:
f = open('DataSet.txt')
for line in iter(f):
remove_blanks = ['']
entries = line.split()
''.join([i for i in entries if i not in remove_blanks])
trash = (entries[0], entries[1])
time = int(entries[2])
column = [int(v) for v in entries[3:]]
def myFun():
print(entries)
print_string = ''
if column[0] == 100:
if column[1] >= 250 and column[2] == 300:
if len(column) >= 9:
digit = [chr(x) for x in column[4:9]]
print_string = ('code: ' + ''.join(str(digit[l]) for l in range(5)) + ' ')
if len(column) >= 13:
optional_digit = [chr(d) for d in column[9:13]]
for m in range(0, 4):
print_string += 'Optional Field: ' + optional_digit[m] + ''
else:
print_string += 'No Optional Field '
pass
pass
print(print_string)
print('')
myFun()
f.close()
What is happening is if the length of a line of my data is not long enough (i.e. the list ends at column[6]), I get the error:
line 17, in function
print('Code: ' + digit[l])
IndexError: list index out of range
I want it to still print Code: #number #number #number #number and leave any non-existent columns as blanks when it is printed so that one line may print as Code: ABC9 and the next print as Code: AB if there are differing list lengths.
Please help! :)
Well, just make sure you're not looping over a list longer than available:
print_string = 'code: ' + ''.join(str(digit[l]) for l in range(min(5, len(digit)))) + ' '
or better:
print_string = "code {} ".format("".join(str(dig) for dig in digit[:5]))
Although I have a feeling you're over-complicating this.
doc = "unsorted.txt"
out_fil = "H:\Grade 11\Intro to Computer Science\sorted.txt" # Used in the Windows variation of the program
out_file = "/Applications/Banter" # Used in the Mac variation of the program
import time
def main():
order = False
blank = []
passcount = 0
starttime = time.time()
numlist = CreateList(doc)
while not order:
passcount = passcount + 1
switch = False
switchcount = 0
print "1" # These are test prints to I used to find problems
for x in range (len(numlist)):
print "2" # These are test prints to I used to find problems
if numlist[x] > numlist[x+1]:
temp = numlist[x+1]
numlist[x+1] = numlist[x]
numlist[x] = temp
switchcount = switchcount + 1
switch = True
print "9" # These are test prints to I used to find problems
elif switch == 0:
order = True
CreateFile(numlist)
endtime = time.time()
print "This list required",endtime-starttime,"seconds to sort."
print "This list required",switchcount,"switches to sort."
print "This list required",passcount,"passes to sort."
def CreateList(doc):
sort = open(doc,"r")
numlist = sort.readlines()
sort.close()
for x in range (len(numlist)):
numlist[x] = int(numlist[x].strip())
return numlist
def CreateFile(numlist):
sort = open(doc,"w")
sort.write(str(numlist)+"\n")
sort.close()
return numlist
def List(numlist):
print numlist
main()
The main purpose of my program is to sort a list of integers from a file in order using the bubble sort method, and then put that list into a new file. I'm also detailing the amount of time it takes to perform this as well as the number of passes and switches within the program that it took to sort it completely.
Now, the problem I'm having is that the list index falls out of range because it's comparing x and x+1 of my numlist. But, I need to compare x+1 in order to sort the two integers beside each others within the list. Is there any way I can fix the program so that it'll compare all the integers in the list and not try to compare the space that isn't in the list because of the x+1?
You could make your loop in this way:
for x in range ( len(numlist) -1 ):
Though stackoverflow is a great resource for answers, giving them up for homework assignments feels like cheating. I'll meet you half way: Make your loop run for one less iteration.
I want to remove some words from a list of words. I have a list with a recurring word and I want to get rid of it and I have no idea. I don't know whether I need to use a whole loop or regex.
from xlrd import open_workbook,error_text_from_code
book = open_workbook(inp)
sheet0 = book.sheet_by_index(0)
x = 0
y = 0
countr = sheet0.nrows
countc = sheet0.ncols
names = ''
variables = []
"different variables-----------------"
while x < countr -1:
x = x+1
y = y+1
cell = sheet0.cell(y,0)
names = names+ str(cell)
cell = sheet0.cell(y,1)
variables.append(cell)
country_text = names
countries = ', '.join(re.findall("('.*?')", country_text))
countries = countries.split()
print (variables)
print (countries)
What I get :
[number:150000.0, number:140000.0, number:300000.0]
and I need
[150000, 140000, 300000]
If you use a loop you can access to the value of a cell using this function:
sheet0.cell_value(curr_row, curr_cell)