Python:将数组分成若干部分
更新:在Jeremy的帮助下,我成功解决了这个问题,他的函数把我的数据集分成了50个小块。我已经发布了最终的答案。
我有以下代码,我想把数组分成小块的原因是因为我正在使用一个只允许同时发送50个请求的API。此外,我是一名Java开发者,正在尝试转向Python。我想做的是把数组分成50个小块,然后把它们发送给API。
我有一个文本文件,里面有一长串的ID,我根据读取到的ID来构建URL。
import simplejson as json
import sys
import urllib
import traceback, csv, string
# "base" API URL
URL_BASE = 'Some URL'
# set user agent string
urllib.version = "Data Collection Fix it"
page_ids = []
def divide_list(list_, n):
for i in range(0, len(list_), n):
yield list_[i:i + n]
def issue_query():
iFile = open('ReadFromThisFile.txt', "r")
lines = iFile.readlines()
#print len(lines)
for line in lines:
ids = string.split(line)
ids = ids[0]
page_ids.append(ids)
url = URL_BASE
indicies = range(len(page_ids))
File = open("WriteToThisFile.csv", "w")
for indicies in divide_list(page_ids, 50):
count = 0
fiftyIds =[]
url = URL_BASE
for id in indicies:
str(id).strip
url += str(id) + '|'
print url
fiftyIds.append(str(id))
count += 1
print count
rv = urllib.urlopen(url)
j = rv.read().decode("utf-8")
#sys.stderr.write(j + "\n")
data = json.loads(j)
for id in fiftyIds:
try:
s = int(data["query"]["pages"][id]["revisions"][0]["size"])
sys.stderr.write("%d\t%d\n" % (int(id), s))
File.write("%d\t%d\n" % (int(id), s))
#print ("%d\t%d\n" % (int(id), s))
# do something interesting with id and s
except Exception, e:
traceback.print_exc()
File.close()
iFile.close()
issue_query()
我知道很多有经验的Python开发者可能会因为我问这样一个简单的问题而给我负面评价,但我在谷歌或这里找不到好的例子。所以如果我重复了一个问题,真的很抱歉。
谢谢,
4 个回答
3
可能有一个内置的函数可以做到这一点,但我想不起来了。
#!/usr/bin/env python2.7
def divide_list(list_, n):
"""Produces an iterator over subsections of maximum length n of the list."""
for i in range(0, len(list_), n):
yield list_[i:i + n]
使用示例:
print(list(divide_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 3)))
# prints: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
像你例子中那样用它来生成网址:
BASE_URL = "http://example.com/blah?ids="
page_ids = range(0, 123)
for indices in divide_list(page_ids, 50):
url = URL_BASE + "|".join(str(i).strip() for i in indices)
# then do something with url...
print(url)
# prints:
# http://example.com/blah?ids=0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32|33|34|35|36|37|38|39|40|41|42|43|44|45|46|47|48|49
# http://example.com/blah?ids=50|51|52|53|54|55|56|57|58|59|60|61|62|63|64|65|66|67|68|69|70|71|72|73|74|75|76|77|78|79|80|81|82|83|84|85|86|87|88|89|90|91|92|93|94|95|96|97|98|99
# http://example.com/blah?ids=100|101|102|103|104|105|106|107|108|109|110|111|112|113|114|115|116|117|118|119|120|121|122
3
在 itertools 的文档 中有一个很不错的教程(真的值得好好看看,这样你就知道什么时候需要用到里面的内容——而且你肯定会需要的)。
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
0
我想我应该直接回答问题,而不是更新我最初提问的内容。希望这样不会让人困惑。我在问题部分添加了更新的评论,告诉大家这个问题已经解决了。下面是我在Jeremy Banks的帮助下解决这个问题的方法。
import simplejson as json
import sys
import urllib
import traceback, csv, string
# "base" API URL
URL_BASE = 'Some URL'
# set user agent string
urllib.version = "Data Collection Fix it"
page_ids = []
def divide_list(list_, n):
for i in range(0, len(list_), n):
yield list_[i:i + n]
def issue_query():
iFile = open('ReadFromThisFile.txt', "r")
lines = iFile.readlines()
#print len(lines)
for line in lines:
ids = string.split(line)
ids = ids[0]
page_ids.append(ids)
url = URL_BASE
indicies = range(len(page_ids))
File = open("WriteToThisFile.csv", "w")
for indicies in divide_list(page_ids, 50):
count = 0
fiftyIds =[]
url = URL_BASE
for id in indicies:
str(id).strip
url += str(id) + '|'
print url
fiftyIds.append(str(id))
count += 1
print count
rv = urllib.urlopen(url)
j = rv.read().decode("utf-8")
#sys.stderr.write(j + "\n")
data = json.loads(j)
for id in fiftyIds:
try:
s = int(data["query"]["pages"][id]["revisions"][0]["size"])
sys.stderr.write("%d\t%d\n" % (int(id), s))
File.write("%d\t%d\n" % (int(id), s))
#print ("%d\t%d\n" % (int(id), s))
# do something interesting with id and s
except Exception, e:
traceback.print_exc()
File.close()
iFile.close()
issue_query()