Python 如何将str分解为列表
这就是我到目前为止所做的:Python 如何将str分解为列表,python,Python,这就是我到目前为止所做的: def file_to_dict(f): """ (file open for reading) -> dict of {float: int} f contains exchange rate changes as floating point numbers separated by whitespace. Return a dict with exchange rate changes as keys and the number of occurre
def file_to_dict(f):
""" (file open for reading) -> dict of {float: int}
f contains exchange rate changes as floating point numbers separated
by whitespace. Return a dict with exchange rate changes as keys and the
number of occurrences of the exchange rate changes as values.
"""
file = open(f, 'r')
data = list(file.read().strip().split('\n'))
数据如下:
0.0045 0.0160 -0.0028 -0.0157 -0.0443 -0.0232 -0.0065 -0.0080 0.0052
-0.0052 -0.0283 -0.0087 -0.0020 -0.0080 -0.0065 -0.0290 0.0180 0.0030
-0.0170 0.0000 -0.0185 -0.0055 0.0148 -0.0053 0.0265 -0.0290 0.0010
-0.0015 0.0137 -0.0137 -0.0023 0.0008 0.0055 -0.0025 -0.0125 0.0040
如何使每个数字成为列表中的一项?
例如:[0.0045,0.0160等]或['0.0045','0.0160'等]类似这样的东西
>>> with open('fileName', 'r') as f:
newList = []
for line in f:
newList.extend(map(float, line.split()))
>>> newList
[0.0045, 0.016, -0.0028, -0.0157, -0.0443, -0.0232, -0.0065, -0.008, 0.0052, -0.0052, -0.0283, -0.0087, -0.002, -0.008, -0.0065, -0.029, 0.018, 0.003, -0.017, 0.0, -0.0185, -0.0055, 0.0148, -0.0053, 0.0265, -0.029, 0.001, -0.0015, 0.0137, -0.0137, -0.0023, 0.0008, 0.0055, -0.0025, -0.0125, 0.004]
因为,你不能使用地图,做一些类似的事情
>>> with open('fileName', 'r') as f:
newList = []
for line in f:
for elem in line.strip().split():
newList.append(float(elem))
因为您不能使用map,也可能没有生成器,所以只需使用2作为循环 此外,听起来您可以使用字符串来存储浮点数,这将有助于提高精度,因为浮点数比较比较混乱
stringlist = []
with open('fileName', 'r') as file:
for line in file:
for item in line.split():
stringlist.append(item) # this stores strings
如果您想计算这些浮动的出现次数并将其存储在dict中,就像您的任务一样,您可以执行以下操作:
myDict = {}
for value in stringlist:
if value in myDict.keys(): # this would pose float comparison issues if you used float keys
myDict[value] += 1
else:
myDict[value] = 1
print myDict
列表理解:
list_ = [
float(number) for line in open("filename", "r")
for number in line.strip().split()
]
我不能使用map函数,我们还没有学会它,因此应该使用其他方法。我直觉上想做的是转到data=listfile.read.strip.split'\n',''或data=listfile.read.strip.split'\n'和'',但这似乎不是split函数的本质谢谢,您的方法起作用了。我还发现,执行data=listfile.read.strip.split同样有效,将每个数字作为一个listCool。很高兴能帮上忙。请随意有关词典的更多帮助,请参见我的答案。为了清晰起见,可以改进此问题的标题