在python中分割和分开

时间:2015-08-10 21:21:12

标签: python algorithm

我是Python的新手,我想知道如何用逗号分隔(,)和冒号(:)。我正在尝试加油站问题,我想从文本文件中读取这样的内容:

1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8

我还想打开并从文件中读取这些数据并将其存储在链表中。

直到现在我做到了:

def GasStation(strArr):
    strArr = []

    f = open('Details.txt', 'r')
    for line in f:
        strArr.append(line)

    amount, tank = int(strArr[0]),0
    stations = [amount.split(":") for i in (strArr[1:] + strArr[1:-1])]
    for curr in range(start, start+amount):
        tank = tank + int(stations[curr][0]) - int(stations[curr][1])
    if tank < 0: sys.exit()
    if tank >= 0: return start+1
    else: tank = 0
    return "not"

我还想打印作为答案的索引。

请帮助我,我不明白为什么不给我打印答案。

感谢。

2 个答案:

答案 0 :(得分:5)

假设您的问题是如何按,然后:拆分给定的序列,您可以使用list comprehensions

>>> numbers = '1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8'
>>> pairs = [pairs.split(':') for pairs in numbers.split(',')]
>>> print pairs
[['1', '1'],
 ['2', '2'],
 ['3', '3'],
 ['4', '4'],
 ['5', '5'],
 ['6', '6'],
 ['7', '7'],
 ['8', '8']]

如果您想要展平列表,可以使用itertools.chain.from_iterable

>>> import itertools
>>> print list(itertools.chain.from_iterable(pairs))
>>> ['1', '1', '2', '2', '3', '3', '4', '4', '5', '5', '6', '6', '7', '7', '8', '8']

为了能够回答您的其他问题,我们需要了解tankamountstations的含义。

答案 1 :(得分:1)

试试这个,我清理了你的代码并删除了一堆错误,尽管我并不完全理解它。 编辑:我添加了全球&#39;这可能是问题

# Did you import sys?
import sys
# You don't need to pass 'strArr', what, you want to initialize it? You don't need to in python.
# I renamed your functions and variables lowercase - its python style to do that
def gas_station():
    # IMPORTANT: you must first declare variables global to modify them
    global tank, stations
    f = open('Details.txt', 'r')
    # you must first read the lines
    # you don't need to loop over it and do that - readlines() returns a list, so you can assign it directly
    strarr = f.readlines()
    # Close your file! 
    # This can lead to memory leaks and make your application use more RAM (although python typically does this for you, you can't rely on that all the time.)
    f.close()
    amount, tank = int(strarr[0]), 0
    stations = [amount.split(":") for i in (strarr[1:] + strarr[1:-1])]
    # I don't understand "start". It was never initialized and I assume its just strarr[0]
    # range(start, start+1) is the same as the tuple(start, start+1), you do not need range
    for curr in (strarr[0], strarr[1]):
        tank = tank + int(stations[curr][0]) - int(stations[curr][1])
    if tank < 0:
        # Don't do that! It's ugly and against PEP 8: https://www.python.org/dev/peps/pep-0008/
        # Also don't exit - raise an exception
        raise ValueError('Tank is less than 0')
    elif tank >= 0:
        return strarr[0] + 1
    else:
        tank = 0
    # False is better and awesomer than just 'not', you can check it just like you can with 'not' and its more pythonic too.
    return False

PEP 8非常重要 - 它可以让其他开发人员看到非PEP8格式的代码,它就像Java中的小写命名变量一样,只有在python中它不是传统 - 它是法律。

您还要更改全局变量,而不是运行函数来返回新结果并将其分配给变量。

我的代码:

# f = open('Details.txt', 'r')
# text = f.read()
# f.close()
text = '1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8'
# This is a list of the lines from the file seperated at the comma like this:
# ['1:1', '2:2', '3:3', '4:4', '5:5', '6:6', '7:7', '8:8']
comma_seperated = text.split(',')
# List comprehension here. This is a ninja skill you'll learn later on here:
# https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions
# It's much faster and beautiful
nested_seperated = [element.split(':') for element in comma_seperated]
# This is the equivalent with a for loop:
nested_seperated = []
for element in comma_seperated:
    nested_seperated.append(element.split(':'))
print(nested_seperated)
# Output: [['1', '1'], ['2', '2'], ['3', '3'], ['4', '4'], ['5', '5'], ['6', '6'], ['7', '7'], ['8', '8']]


# If you want to make them integers instead, replace the list comprehension with this other one:
nested_seperated = [[int(i) for i in element.split(':')] for element in comma_seperated]
# int() can turn strings into integers
# or this equivalent for loop:
nested_seperated = []
for element in comma_seperated:
    inner = []
    for i in element.split(':'):
        inner.append(int(i))
    nested_seperated.append(inner)
print(nested_seperated)
# Output: [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6], [7, 7], [8, 8]]

我假设您在输入中没有任何换行符。

我不明白为什么你需要一个链表,因为它是一个复杂的CS结构,但如果你的意思是字典,那就干这样做:

dictionary_version = dict(nested_seperated)
# Output: {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8}