如何在Python中设置生成单词列表的开始和停止输入

问题描述 投票:2回答:1

我努力想弄清楚如何为我的Python wordlist生成器输入启动和停止单词。

这是我的代码:

import itertools

   wrds = 'abcd0123'
   n = 5

   for i in itertools.product(wrds, repeat = n):
      a = ''.join(i)
      print(a)

我的发电机像往常一样给我这样的输出:aaaaaaaaabaaaac,...

但是如何设置输入以获取起点和终点?

我的长度是5.我想例如从aaac1到aaad3生成。我怎样才能做到这一点?我完全卡住了。

python python-3.x
1个回答
1
投票

非常普遍和初学者的做法是

import itertools

start_string=input("Enter start string: ")
end_string=input("Enter ending string: ")

wrds = 'abcd0123'
n = 5
empty_list=[]

for i in itertools.product(wrds, repeat = n):
    empty_list.append(''.join(i))

if start_string in empty_list:
    start_=empty_list.index(start_string)


if end_string in empty_list:
    end_=empty_list.index(end_string)

print(empty_list[start_:end_+1])

要逐行输出,请使用以下代码替换最后一个print语句

for item in empty_list[start_:end_+1]:
    print(item)

如果你想以随机索引顺序传递起始字符串和结束字符串,如果你想让代码本身决定索引,那么你可以使用下面的代码

import itertools

string_1=input("Enter start string: ")
string_2=input("Enter ending string: ")

wrds = 'abcd0123'
n = 5
empty_list=[]

for i in itertools.product(wrds, repeat = n):
    empty_list.append(''.join(i))

if string_1 in empty_list:
    index_1=empty_list.index(string_1)

if string_2 in empty_list:
    index_2=empty_list.index(string_2)

if index_1 > index_2 :
    start_ = index_2
    end_ = index_1 + 1
else :
    start_ = index_1
    end_ = index_2+1

for item in empty_list[start_:end_]:
    print(item)

要获得计数,可以使用len()函数

print("Length: ", len(empty_list[start_:end_]))

如果你试图找到Python基础知识的良好开端,我建议你阅读https://docs.python.org/3.6/tutorial/index.html。它非常小,可以在一天内阅读。

© www.soinside.com 2019 - 2024. All rights reserved.