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

Reading from pipe stdout waits infinitely
Getting Slice of one dimension in ndarray
Parsing Tex using python re library
Fix the seed for the community module in Python that uses networkx module
select first n items of a list without using a loop.
when I initiate second button click -> AttributeError: Application instance has no attribute 'readfile'
Python 3.4 with an older Python script for use in Blender, TypeErrors
error when installing numpy for pypy2.2.1
How to find out in which locale it was encoded to?
alembic revision - multiple heads (due branching) error
Python set value multiindex Pandas
Multiplication table for double digit numbers using nested loops in Python
pandas time_range does not start from start date
Django How about my method to solve anti spam post request? Is there better solutions?
How can I write a csv file with multiple header lines with pandas to_csv()?
Connect to RDS from EC2 instance with Python

Categories

HOME
redis
shopify
crate
jsviews
amazon-product-api
transparent
zend-framework2
jscript
checksum
value
gimp
vuex
gatsby
equalizer
sign
uisplitviewcontroller
distance
source-maps
tflearn
python-textprocessing
hanami
opencart2.3
datadog
autofill
red-black-tree
lmdb
salesforce-chatter
transient
powershell-remoting
oscommerce
mmdrawercontroller
bigcartel
strstr
common.logging
pytest-django
rkt
estimation
w3-total-cache
production-environment
multi-agent
greenhills
pycurl
python-hypothesis
emoticons
communication-protocol
cleditor
spring-ioc
xib
cron-task
zurb-foundation-apps
pax-web
spatial-query
console-redirect
aerogear
qt-linguist
git-rebase
void
data-import
app.xaml
subresource-integrity
built-in
crash-dumps
callstack
httpie
jai
django-1.6
gmaps4rails
candidate-key
microblaze
libssh2
funq
bsp
dbsetup
crystal-reports-10
lov
bsod
visual-studio-addins
exiv2
pyjade
nservicebus4
nimrod
symphony-cms
objcmongodb
cbcentralmanager
datarepeater
redirectstandardoutput
expression-evaluation
z-machine
point-sprites
flash-cs5.5
gtk2hs
open-graph-beta
asp.net-routing
sitemappath
camtasia
savestate
nt4

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