我是Python新手,我想知道如何用逗号(,)和冒号(:)进行分割。 我正在尝试加油站问题,我想从这样构建的文本文件中读取:
11:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8
我还想打开并从文件中读取此数据并将其存储在链接列表中。
到目前为止,我做到了:
15def 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"我也想打印索引就是答案。
请帮助我,我不明白为什么我的答案没有打印出来。
谢谢。
您要先用逗号替换冒号。 stackoverflow.com/questions/10017147/
为什么要链接列表? 标准list有什么问题?
不要忘记关闭文件。 您最后的tank=0分配没有执行任何操作; 当您在下一行退出函数时,它是一个超出范围的局部变量。
给定整数序列,tank,amount和stations是什么意思?
@亚历山大有一点。 使用with语句不处理很容易滑过的f.close()。
@ yahav10请参阅我的编辑答案
假设您的问题是如何按,然后按:拆分给定序列,则可以使用列表推导:
11>>> 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:
3>>> 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']为了使我们能够回答您的其他问题,我们需要知道您所说的tank,amount和stations是什么意思。
那给了他一个清单清单,不是吗? 不应为[1、1、2、2]。 除非那是他想要的。 哇。 itertools是坚固的#pro
尝试一下,我清理了您的代码并删除了许多错误,尽管我不太了解。编辑:我添加了"全局"可能是问题所在
30# 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 FalsePEP 8非常重要-它可以使其他开发人员欣喜地看到非PEP8格式的代码,就像在Java中将变量命名为小写字母一样,仅在python中这不是传统-这是法律。
您还正在更改全局变量,而不是运行函数以返回新结果并将其分配给变量。
我的代码:
31# 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结构,但是如果您是用字典指的,只需执行以下操作:
1
2dictionary_version = dict(nested_seperated)
# Output: {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8}James Lu,谢谢您的更改,我已经记下了它,我将遵循PEP 8并将坚持下去。 我想知道算法找到解决方案时是否打印索引? 如果是这样,它在哪一行?
















