简体   繁体   English

在 python 中的循环中更改循环变量

[英]Changing a loop variable within the loop in python

I am building a small script to perform a task.我正在构建一个小脚本来执行任务。 I am using a for loop in a section of my code to give me a list, however, I need the list to not be in perfect order as its being generated.我在我的代码的一部分中使用for循环来给我一个列表,但是,我需要列表在生成时没有完美的顺序。 To do this I attempted to reverse the string variable “chat” within the loop in the hopes of affecting the value of the loop variable.为此,我尝试在循环中反转字符串变量“chat”,以期影响循环变量的值。

However, my code doesn't seem to be doing that since I get a clean aaa , aab , etc. output when it runs, regardless if I comment out the line char = char[::-1] or not.但是,我的代码似乎没有这样做,因为我在运行时得到了干净的aaaaab等输出,无论我是否注释掉char = char[::-1]

Is what I am trying to do possible with for loop?我正在尝试用 for 循环做的事情可能吗? Or is there any other way to this?或者有没有其他方法可以做到这一点? And how can I get a more random order in my result in another way?我怎样才能以另一种方式在我的结果中获得更随机的顺序?

Also, I am using the list to make sure I don't get duplicates and I am printing char at the end to make sure it's changed except it doesn't seem to be going through the loop.此外,我正在使用该列表来确保我没有得到重复,并且我在最后打印 char 以确保它已更改,除非它似乎没有通过循环。

Here is the code.这是代码。

import time 
import itertools

char = "abc"
counter = 0
x = []
for i in itertools.product(char, repeat=3):
    if ''.join(i)in x:
        break

    print(''.join(i))
    counter += 1
    char = char[::-1]
    x.append(''.join(i))

print('[+] Printed ' + str(counter)+ ' charecters.')

print(char)

Not sure what you are asking about, but let me try to solve the problem you have :)不确定您在问什么,但让我尝试解决您遇到的问题:)

import itertools
from random import shuffle

char = "abc"

items = [''.join(x) for x in itertools.product(char, repeat=len(char))]
shuffle(items)

print('\n'.join(items))
print('[+] Printed {} charecters.'.format(len(items)))
python test123.py
bbb
aca
bcb
abb
aab
bcc
acb
cca
abc
ccc
cac
caa
ccb
bca
cbb
bba
aba
aac
baa
bab
bac
cbc
bbc
acc
aaa
cab
cba
[+] Printed 27 charecters.

every run it generates the same "products list" but in a different order每次运行都会生成相同的“产品列表”,但顺序不同

Superfast "product" list generator with randomized output under the hood!具有随机输出的超快“产品”列表生成器!

I've spent some time and got the working example我花了一些时间并得到了工作示例

import itertools
from contextlib import contextmanager
from random import shuffle, sample
from datetime import datetime

char = "abcdefgf"


def generate_product(char):
    items = []
    for i, item in enumerate(itertools.product(char, repeat=len(char))):
        items.append("".join(item))
    shuffle(items)

    return items


def generate(char):
    pools = (char,) * len(char)

    result = ['']
    for i, pool in enumerate(pools):
        # let's shuffle the pool, it will randomize output without extra performance hit
        pool_rnd = sample(pool, k=len(pool))

        result = [x + y for x in result for y in pool_rnd]

    return result


@contextmanager
def timeit(name):
    start = datetime.now()
    print('Started "{}" at {}. Please wait ...'.format(name, start))

    yield

    end = datetime.now()
    print('Finished "{}" at {}! Execution took {}'.format(name, start, end - start))


with timeit('generate_product'):
    items1 = generate_product(char)
    # # print('\n'.join(items1))
    print(' > Contains {} charecters.'.format(len(items1)))

with timeit('generate'):
    items2 = generate(char)
    # print('\n'.join(items2))
    print(' > Contains {} charecters.'.format(len(items2)))

print('Are equal? Sorted comparision result={}'.format(sorted(items1) == sorted(items2)))

Compare the speed!比较速度!

#> python test123.py

Started "generate_product" at 2019-12-13 05:35:39.219348. Please wait ...
 > Contains 16777216 charecters.
Finished "generate_product" at 2019-12-13 05:35:39.219348! Execution took 0:00:30.075320
Started "generate" at 2019-12-13 05:36:09.294871. Please wait ...
 > Contains 16777216 charecters.
Finished "generate" at 2019-12-13 05:36:09.294871! Execution took 0:00:02.998755
Are equal? Sorted comparision result=True

Just 0:00:02.998755 against 0:00:30.075320 !只是0:00:02.9987550:00:30.075320 That's a victory I believe!这是我相信的胜利!

One more "stress-test" for the algorithm!算法的另一项“压力测试”!

Started "generate" at 2019-12-13 05:39:01.434788.在 2019-12-13 05:39:01.434788 开始“生成”。 Please wait ... Contains 387420489 charecters.请稍候... 包含 387420489 个字符。 Finished "generate" at 2019-12-13 05:39:01.434788!在 2019-12-13 05:39:01.434788 完成“生成”! Execution took 0:01:20.306413执行时间为 0:01:20.306413

80 seconds to generate list of 387_420_489 combinations! 80 秒生成 387_420_489 个组合列表! I consumed 25 GB or RAM :D我消耗了 25 GB 或 RAM :D

You are changing char inside the loop, which is iterating over product(char, repeat=3) .您正在循环内更改char ,它正在迭代product(char, repeat=3)

Although char is changed every time (you can check this by printing it), it does not affect the data you're looping over.尽管每次都会更改char (您可以通过打印来检查它),但它不会影响您循环的数据。 That makes sense if you think about it: what would you expect would happen exactly?如果您考虑一下,这是有道理的:您预计会发生什么?

The loop simply completes iterating over the original product and every value will show up in order, reversing char does nothing.循环简单地完成对原始产品的迭代,每个值都将按顺序显示,反转char什么也不做。

If you were trying to show all three character combinations of characters from the original string, but in a random order, this would work:如果您尝试显示原始字符串中字符的所有三个字符组合,但以随机顺序显示,这将起作用:

import random
import itertools

chars = 'abc'

result = list(itertools.product(chars, repeat=3))
random.shuffle(result)

for x in result:
    print(''.join(x))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM