我目前在转换列表中列表中的元素时遇到问题。
注意:我试图避免列表[0]中的第一个列表,因为我不希望它通过删除它是一个整数。
import urllib.request
def readWordList(urlData):
response = urllib.request.urlopen ("http://www.cs.queensu.ca/home/cords2/marks.txt")
html = response.readline()
data = []
while len(html) != 0:
line = html.decode('utf-8').split()
data.append(line)
html = response.readline()
del data[0]
return data
print (readWordList("http://www.cs.queensu.ca/home/cords2/marks.txt"))
以下是我目前情况的一些图片
我在列表中得到了我的列表,但信息形成了字符串,我想将元素更改为整数。我怎么能这样做?
答案 0 :(得分:0)
在返回数据之前,你可以在python 2中找到类似的内容:
for index,element in enumerate(data):
data[index] = map(int, element)
或
for index,element in enumerate(data):
data[index] = [int(i) for i in element]
或在Python 3中
for index,element in enumerate(data):
data[index] = list(map(int, element))
例如,您的代码将变为类似
import urllib.request
def readWordList(urlData):
response = urllib.request.urlopen ("http://www.cs.queensu.ca/home/cords2/marks.txt")
html = response.readline()
data = []
while len(html) != 0:
line = html.decode('utf-8').split()
data.append(line)
html = response.readline()
del data[0]
for index,element in enumerate(data):
data[index] = map(int, element)
return data
print (readWordList("http://www.cs.queensu.ca/home/cords2/marks.txt"))