打印如果元组中的原点是[0](python)

时间:2014-04-22 12:36:13

标签: python python-3.x

我想格式化我的代码,以便在调用river时打印单词sandvalue[0]

datafile.txt

river, 4
-5, 6
-6, 8
6, 9

sand, 10
6, 7
-6, 76
-75, 75

我的代码

textFile =open("datafile.txt", "r")
dataString = textFile.read()

value=[]
for split in dataString.split('\n\n'):
    split = ','.join(split.split('\n'))
    split = ''.join(split.split(' '))
    split = split.split(',')
    for 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()

上面的代码打印出"river", (0,4),(-5,6),(-6,8),(6,9), "sand", (0,10), (6,7),(-6,76),(-75,75)之类的内容。我希望它在调用value [0]时打印河流和沙子。我如何更改我的代码来做到这一点?数据来自文本文件。

调用value[0]时的预期输出应仅打印"river""sand",而忽略所有其他输出,并且当调用value[1:]时,除了{的值外,其他所有内容都会打印{1}}和"sand"

还应检查"river"的值:

value[0]

3 个答案:

答案 0 :(得分:1)

和其他人一样,我并不完全理解这个要求,但这是我的看法:

value = zip(*[stanza.split(',') for stanza in dataString.split('\n\n')])

这会导致value[0]打印" 字符串" river"和#34; sand" ",而value[1:]打印" 其他一切"。

答案 1 :(得分:0)

我不确定我理解你的问题,但我认为这可能会做你想要的:

textFile =open("datafile.txt", "r")
dataString = textFile.read()

res =  dataString.replace(',',' ').split()

value = [[i for i in res if i.isalpha()] , [i for i in res if not i.isalpha()]]

答案 2 :(得分:0)

我认为这样做符合你的要求:

#!/usr/bin/env python

textFile =open("datafile.txt", "r")

# construct list of non-empty lines
# strip trailing newline and split on ','
lines = [l for l in (m.rstrip('\n').split(',') 
                     for m in textFile.readlines()) if len(l) > 1]

# make tuple from names
names = tuple(a for a,b in lines if a.isalpha())

# prepend names to list of tuples built from each line
# alphabetical entries are substituted for 0s
value = [names] + [(0,b) if a.isalpha() else (a,b) for a,b in lines]

print value

编辑:我认为这种做法更为清晰:

#!/usr/bin/env python

# use "with" to avoid having to close the file
with open("datafile.txt") as textFile:
    # get array containing all values in the file
    v = textFile.read().replace(',','').split()
    # extract the names into a separate tuple
    names = [tuple(filter(str.isalpha, v))]
    # make tuples out of each pair of values, replacing names with zeroes
    values = [(0,b) if a.isalpha() else (a,b) for a,b in zip(v[::2], v[1::2])]
    # concatenate the two
    values = names + values

print values

输出:

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