Print if origin in tuple is [0] (python) -


i format code print the word river , sand if value[0] called.

datafile.txt

river, 4 -5, 6 -6, 8 6, 9  sand, 10 6, 7 -6, 76 -75, 75 

my code

textfile =open("datafile.txt", "r") datastring = textfile.read()  value=[] split in datastring.split('\n\n'):     split = ','.join(split.split('\n'))     split = ''.join(split.split(' '))     split = split.split(',')     x in range(0, len(split)-1):         if (x == 0):             value.append(split[x])             value.append((0, split[x+1]))         else:             temptuple=(split[x], split[x+1])             value.append(temptuple) print(value[0]) datafile.close() 

the above code prints "river", (0,4),(-5,6),(-6,8),(6,9), "sand", (0,10), (6,7),(-6,76),(-75,75). it print river , sand when value[0] called. how change code that? data comes text file.

the expected output when value[0] called should print "river" , "sand" while others ignored , when value[1:] called else prints except values of "sand" , "river".

also values of value[0] should checked:

label = value[0] if (label=='river'):   print("river") elif (label=='sand')   print("sand") 

i think want:

#!/usr/bin/env python  textfile =open("datafile.txt", "r")  # construct list of non-empty lines # strip trailing newline , split on ',' lines = [l l in (m.rstrip('\n').split(',')                       m in textfile.readlines()) if len(l) > 1]  # make tuple names names = tuple(a a,b in lines if a.isalpha())  # prepend names list of tuples built each line # alphabetical entries substituted 0s value = [names] + [(0,b) if a.isalpha() else (a,b) a,b in lines]  print value 

edit: think approach little cleaner:

#!/usr/bin/env python  # use "with" avoid having close file open("datafile.txt") textfile:     # array containing values in file     v = textfile.read().replace(',','').split()     # extract names separate tuple     names = [tuple(filter(str.isalpha, v))]     # make tuples out of each pair of values, replacing names zeroes     values = [(0,b) if a.isalpha() else (a,b) a,b in zip(v[::2], v[1::2])]     # concatenate 2     values = names + values  print values 

output:

[('river', 'sand'), (0, ' 4'), ('-5', ' 6'), ('-6', ' 8'), ('6', ' 9'), (0, ' 10'), ('6', ' 7'), ('-6', ' 76'), ('-75', ' 75')] 

Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -