- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
所以我写了一个小脚本来从网站下载图片。它通过一个 7 字母字符值,其中第一个字符始终是一个数字。问题是如果我想停止脚本并重新启动它,我必须重新开始。
我能否以某种方式将我获得的最后一个值作为 itertools.product 的种子,这样我就不必再次遍历它们。
感谢任何输入。
部分代码如下:
numbers = '0123456789'
alnum = numbers + 'abcdefghijklmnopqrstuvwxyz'
len7 = itertools.product(numbers, alnum, alnum, alnum, alnum, alnum, alnum) # length 7
for p in itertools.chain(len7):
currentid = ''.join(p)
#semi static vars
url = 'http://mysite.com/images/'
url += currentid
#Need to get the real url cause the redirect
print "Trying " + url
req = urllib2.Request(url)
res = openaurl(req)
if res == "continue": continue
finalurl = res.geturl()
#ok we have the full url now time to if it is real
try: file = urllib2.urlopen(finalurl)
except urllib2.HTTPError, e:
print e.code
im = cStringIO.StringIO(file.read())
img = Image.open(im)
writeimage(img)
câu trả lời hay nhất
这里有一个基于pypy库代码的解决方案(感谢agf在评论中的建议)。
状态可通过 .state
属性获得,并可通过 .goto(state)
重置,其中 state
是序列(从 0 开始)。最后有一个演示(恐怕你需要向下滚动)。
这比丢弃值要快得多。
> cat prod.py
class product(object):
def __init__(self, *args, **kw):
if len(kw) > 1:
raise TypeError("product() takes at most 1 argument (%d given)" %
len(kw))
self.repeat = kw.get('repeat', 1)
self.gears = [x for x in args] * self.repeat
self.num_gears = len(self.gears)
self.reset()
def reset(self):
# initialization of indicies to loop over
self.indicies = [(0, len(self.gears[x]))
for x in range(0, self.num_gears)]
self.cont = True
self.state = 0
def goto(self, n):
self.reset()
self.state = n
x = self.num_gears
while n > 0 and x > 0:
x -= 1
n, m = divmod(n, len(self.gears[x]))
self.indicies[x] = (m, self.indicies[x][1])
if n > 0:
self.reset()
raise ValueError("state exceeded")
def roll_gears(self):
# Starting from the end of the gear indicies work to the front
# incrementing the gear until the limit is reached. When the limit
# is reached carry operation to the next gear
self.state += 1
should_carry = True
for n in range(0, self.num_gears):
nth_gear = self.num_gears - n - 1
if should_carry:
count, lim = self.indicies[nth_gear]
count += 1
if count == lim and nth_gear == 0:
self.cont = False
if count == lim:
should_carry = True
count = 0
khác:
should_carry = False
self.indicies[nth_gear] = (count, lim)
khác:
phá vỡ
def __iter__(self):
trả lại chính mình
def next(self):
if not self.cont:
raise StopIteration
l = []
for x in range(0, self.num_gears):
index, limit = self.indicies[x]
l.append(self.gears[x][index])
self.roll_gears()
return tuple(l)
p = product('abc', '12')
print list(p)
p.reset()
print list(p)
p.goto(2)
print list(p)
p.goto(4)
print list(p)
> python prod.py
[('a', '1'), ('a', '2'), ('b', '1'), ('b', '2'), ('c', '1'), ('c', '2')]
[('a', '1'), ('a', '2'), ('b', '1'), ('b', '2'), ('c', '1'), ('c', '2')]
[('b', '1'), ('b', '2'), ('c', '1'), ('c', '2')]
[('c', '1'), ('c', '2')]
你应该多测试一下 - 我可能犯了一个愚蠢的错误 - 但这个想法很简单,所以你应该能够修复它 :o) 你可以自由使用我的更改;不知道原始的 pypy 许可证是什么。
还有 state
并不是真正的完整状态——它不包括原始参数——它只是序列的索引。也许称它为索引会更好,但是代码中已经有索引了……
gia hạn
这是一个更简单的版本,它的想法相同,但通过转换数字序列来工作。所以你只需 imap
它超过 count(n)
就可以得到 N
的序列偏移量。
> cat prod2.py
from itertools import count, imap
def make_product(*values):
def fold((n, l), v):
(n, m) = divmod(n, len(v))
return (n, l + [v[m]])
def product(n):
(n, l) = reduce(fold, values, (n, []))
if n > 0: raise StopIteration
return tuple(l)
return product
print list(imap(make_product(['a','b','c'], [1,2,3]), count()))
print list(imap(make_product(['a','b','c'], [1,2,3]), count(3)))
def product_from(n, *values):
return imap(make_product(*values), count(n))
print list(product_from(4, ['a','b','c'], [1,2,3]))
> python prod2.py
[('a', 1), ('b', 1), ('c', 1), ('a', 2), ('b', 2), ('c', 2), ('a', 3), ('b', 3), ('c', 3)]
[('a', 2), ('b', 2), ('c', 2), ('a', 3), ('b', 3), ('c', 3)]
[('b', 2), ('c', 2), ('a', 3), ('b', 3), ('c', 3)]
(这里的缺点是,如果你想停止并重新启动,你需要自己跟踪你已经使用了多少)
关于python - 使用 itertools.product 并希望播种一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9864809/
从 PHP7 开始,为 PRNG 引入了一个新函数:random_int ( http://php.net/manual/en/function.random-int.php ) PHP 手册中没有与
在 .net 核心项目中,我像这样在 Program.cs 文件中播种: var host = BuildWebHost(args); using (var scope = host.Services
我有一张谷歌地图,上面有大约 200 个标记。使用谷歌距离矩阵服务,我可以找到从一个地址到 map 上所有标记的行驶距离。由于 API 限制,我每次调用只能提交 25 个目的地,因此我必须将操作分解为
下面的脚本抛出错误(自定义字段未定义)。我需要以不同的方式传递元素 ID 吗? 我正在尝试使用我要计算的表单字段来为数组播种。它应该迭代数组中的每个表单字段,并用表单元素的值递增 sum 变量。 jQ
我正在学习“Laravel 5 Essentials”中的教程。当我尝试使用命令为我的数据库播种时 php artisan db:seed 我收到错误 [ReflectionException]
我正在关注 docs为 users 表设置种子,该表显示正在使用 User::create class UserTableSeeder extends Seeder { public func
让我首先说明我要完成的任务: 我需要在一定范围内随机生成一组数字 我希望这些数字稍微均匀分布 我需要能够为随机数生成播种,这样,给定一个种子,生成的随机数将始终相同。 在对 drand48()、ran
这个问题在这里已经有了答案: Recommended way to initialize srand? (15 个答案) 关闭 9 年前。 我学习的方法是最初使用 srand(time(NULL))
SQLite 是否支持播种 RANDOM() 的功能与 MySQL 对 RAND() 的处理方式相同? $query = "SELECT * FROM table ORDER BY RAND(" .
我正在使用不支持的 Visual Studio 2010 ,所以我必须播种 default_random_engine .因此,我决定用 rand 播种它如下 srand((unsigned int
在 google OR-tools 库中,“原始”CP-Solver(此处讨论: https://developers.google.com/optimization/cp/original_cp_s
我正在尝试为 AspNetRole 表设置初始系统角色。 播种扩展: public static void EnsureRolesAreCreated(this IApplicationBuilder
我似乎无法弄清楚如何使用 Sequelize 为 ARRAY(ENUM) 播种。当我通过我的应用程序注册用户时,我可以很好地创建一个新用户,但是当我在种子文件中使用 queryInterface.bu
以下代码应创建两个具有相同种子的 Random 对象: System.out.println("System time before: " + System.currentTimeMillis());
尝试从集合中选择伪随机元素时,我看到了非确定性行为,即使 RNG 已播种(示例代码如下所示)。为什么会发生这种情况,我是否应该期望其他 Python 数据类型表现出类似的行为? 注意:我只在 Pyth
关于在 openssl/bn.h 中使用 BN_generate_prime 生成质数的内容,我无法找到答案。另外,我将如何播种此函数使用的任何 PRNG? 单独的问题但与我的代码相关(我正在编写一个
所以,我是 MEAN 堆栈的新手,我在尝试播种 MongoDB 时碰壁了。我正在使用 Mongoose 与数据库进行通信,并且有一堆文档建议我应该能够使用填充的 JSON 文件进行播种。 我尝试过的:
我有一个非常简单的情况:我想使用 testcontainers 测试 AWS 中现有的 mysql 数据库。 我遵循了官方指南( https://www.testcontainers.org/modu
我有一个很长(500K+ 行)的两列电子表格,如下所示: Name Code 1234 A 1234 B 1456 C 4556 A 4556 B 4556
我有一个要播种的数据透视表。除了 PK 和 FK,该表还包含另外两列:Arrival & Departure(类型:时间戳)。我正在使用 Carbon 随机填充前面的列。这是我的代码: $faker
Tôi là một lập trình viên xuất sắc, rất giỏi!