python


Python. Trying to get index[0] == index[1]


i get a index out of range error when i run this code. it works if tmp > 3 and if tmp[2] == tmp[3]. im trying to write to file the numbers in index[0] when conditions are met. aka tmp[0] == tmp[1]. Why is I can't call tmp[0], no matter what I've tried.
i = 0
tmp = []
while(i < len(sequence)):
tmp = sequence[i].replace("(","").replace(")","").split(",")
if(len(tmp) > 1):
if(tmp[0] == tmp[1]):
print tmp[0]
with open(output_file1, 'a') as output:
output.write(str(tmp[0]) + '\n')
i = i+1
return True
python app.py
Traceback (most recent call last):
File "app.py", line 71, in <module>
generate(6, out_path2,out_path1, out_path)
File "app.py", line 45, in generate
random6th = random.choice(sequence2).replace("[", "").replace("]","").replac
e("'","").replace(" ","")
File "C:\Python27\lib\random.py", line 275, in choice
return seq[int(self.random() * len(seq))] # raises IndexError if seq is emp
ty
IndexError: list index out of range
i = 0
tmp = []
while(i < len(sequence)):
tmp.append(sequence[i].replace("(","").replace(")","").split(","))
if(len(tmp) > 0):
if(tmp[0] == tmp[1]):
print tmp[0]
with open(output_file1, 'a') as output:
output.write(str(tmp[0]) + '\n')
i = i+1
return True
Traceback (most recent call last):
File "app.py", line 69, in <module>
generate_2(seq_path, out_path1, out_path2);
File "app.py", line 20, in generate_2
if(tmp[0] == tmp[1]):
IndexError: list index out of range
With the 2nd code I got another traceback error, at if(tmp[0] == tmp[1]
With PRINT tmp[0], never runs cuz of the above error with 2nd code traceback.
A sequence looks like this
(8, 16, 5, 5, 65, 27)
(7, 15, 4, 4, 64, 26)
(21, 17, 12)
(22, 22, 11, 11, 59, 24)
(21, 21, 10, 9, 58, 23)
I'm trying to match 21 and 21 tmp[0] == tmp[1] and then write to file 21.
You're setting tmp = [] before your while loop, but then you re-assign it every time you're in the loop. Your code should instead be:
i = 0
tmp = []
while(i < len(sequence)):
tmp.append(sequence[i].replace("(","").replace(")","").split(","))
if(len(tmp) > 1):
if(tmp[0] == tmp[1]):
print tmp[0]
with open(output_file1, 'a') as output:
output.write(str(tmp[0]) + '\n')
This might resolve your issues.
Ok, it looks like that data is in a list of strings (given that you are calling string methods), so with that assumption, this should work:
# sequences = \
# """(8, 16, 5, 5, 65, 27)
# (7, 15, 4, 4, 64, 26)
# (21, 17, 12)
# (22, 22, 11, 11, 59, 24)
# (21, 21, 10, 9, 58, 23)"""
# sequences = sequences.split('\n')
# Alternatively, if the data is within a textfile called sequence.txt
with open(os.path.join(home_dir, 'sequence.txt'), 'r') as infile:
sequences = infile.read().splitlines(keepends=False)
output_file1 = 'good_sequences.txt'
# assuming you were using mode='a' only because open was called each iteration, otherwise change to 'a'
with open(output_file1, 'w') as outfile:
for sequence in sequences:
seq_data = sequence.replace('(', '').replace(')', '').replace(' ', '').split(',')
if seq_data and len(seq_data) > 2:
if seq_data[0] == seq_data[1]:
print(seq_data[0])
# didn't see a need to cast as str
outfile.write(seq_data[0] + '\n')
The output will be:
22
21
easiest way i solved this was change int(tmp[0]) == int(tmp[1]) did the trick works beautifully now.

Related Links

Call a Python function from a Jinja template
Python Struct Library appending unwanted Char 'L'
Python 3.4 Rock Paper Scissors
Timed Actions - Randomized
Split pandas column into two
Case insensitive field in Django
How to rewrite the code which appends to lists with numpy arrays
Figure in a figure in a figure
Cron job not working all the way. and Python is only half working on my script
Module vtkCommonCorePython not found in windows
Trying to use exec() to define a variable by setting a string equal to a numpy ndarray, but I get a syntax error. Python 2.7.10
Django Staticfiles not being served on Azure
Create virtualenv with most recent version of python
Python date function bugs
Maya/Python: How do I scale multiple selected animation curves each from their own specific pivot point?
django model instance in form without model

Categories

HOME
sql-server-2008
dotnetrdf
sidekiq
ssas-2012
app-inventor
answer-set-programming
freepascal
otrs
heap-memory
shader
getorgchart
spinnaker
gwtp
simple-injector
glpk
datagrip
session-timeout
factor-analysis
pyephem
movies
kitematic
spring-ws
go-cd
croppic
hash-collision
maximo
spring-data-neo4j
ab-initio
dpi
mangodb
vertex-buffer
bxslider
websauna
percentage
pyscripter
m2e
superpowered
lego
jboss-esb
nlb
.net-assembly
codesys
socketpair
coreclr
s3cmd
parent
cross-entropy
intersystems-ensemble
rdw
ti-basic
jgraph
maintenance
chrome-remote-desktop
fontconfig
garrys-mod
pdfkit
efxclipse
sql-server-administration
activeweb
firepath
interactive-brokers
fortran90
spservices
except
plone-3.x
optionbutton
registrykey
sem
windowlistener
stream-framework
xjc
lines-of-code
callstack
word-2013
jai
cloudpebble
omnifocus
ibmsbt
dalekjs
csplit
getimagedata
argument-passing
android-json-rpc
chrome-for-android
healthvault
visual-studio-addins
nsmatrix
swrl
dig
windows-update
adomd.net
fortran77
arbor.js
gdataxml
dropdownlistfor
css-tables
expression-evaluation
getstring
z-machine
wchar
sendfile
pureftpd
email-spec
hibernate3-maven-plugin
hardware-acceleration
iphone-sdk-3.2
oggvorbis
scatterview
revision
castle-validators

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App