小白初学 Python ,有没有大佬可以帮忙简化一下代码

2021-07-22 22:37:31 +08:00
 LinusChen
import pandas as pd
import openpyxl
#用来保存结果的列表
two = []
urltwo = []
urltwoo = []

three = []
urlthree = []
urlthreee = []


four = []
urlfour = []
urlfourr = []

five = []
urlfive = []
urlfivee = []

letters = "abcdefghijklmnopqrstuvwxyz"

#几位数,自己定
ttwo = [a+b for a in letters for b in letters]
tthree = [a+b+c for a in letters for b in letters for c in letters]
ffour = [a+b+c+d for a in letters for b in letters for c in letters for d in letters]
ffive = [a+b+c+d+e for a in letters for b in letters for c in letters for d in letters for e in letters]
#域名后缀
hz = "logistics.com.br"
hz2 = "comex.com"

#开始
for k2 in ttwo:
url2 = [k2 + hz]
url22 = [k2 + hz2]

urltwo.append(url2)
urltwoo.append(url22)
two = urltwo + urltwoo


for k3 in tthree:
url3 = [k3 + hz]
url33 = [k3 + hz2]

urlthree.append(url3)
urlthreee.append(url33)
three = urlthree + urlthreee


for k4 in ffour:
url4 = [k4 + hz]
url44 = [k4 + hz2]

urlfour.append(url4)
urlfourr.append(url44)
four = urlfour + urlfourr

for k5 in ffive:
url5 = [k5 + hz]
url55 = [k5 + hz2]

urlfive.append(url5)
urlfivee.append(url55)
five = urlfive + urlfivee

#导出结果
data = {'两个字母': two,'三个字母': three,'四个字母': four,'五个字母':five}
frame = pd.DataFrame(data)
frame.to_excel("E:\BaiduNetdiskWorkspace\个人\python\猜域名.xlsx")
2263 次点击
所在节点    Python
7 条回复
jaredyam
2021-07-22 23:34:44 +08:00
你这已经不是简化的问题了,看了一半,提出两点提醒:
1. 让变量名具有一定含义
2. letters 这个变量可以通过标准库 import string; string.ascii_lowercase 进行调用
wlsnx
2021-07-23 01:05:39 +08:00
你可以试试 itertools.product
ttwo = [''.join(chars) for chars in product(letters, repeat=2)]
或者用 ttwo * letters 去生成 tthree
tthree = [char + word for char in letters for word in ttwo]
或者用 letters * two 去生成 three
three = [[char + url[0]] for char in letters for url in two],这里顺序会不一致,如果要顺序一致,可以用 letters * two[0:len//2] + letters * two[len//2:]
princelai
2021-07-23 10:24:29 +08:00
应该是用排列吧,from itertools import permutations

字符串相加可以放到 dataframe 里批量去加,这样比在循环里加然后 append 快很多
RichXu
2021-07-23 11:08:17 +08:00
这个命名看得我脑阔疼
xingheng
2021-07-24 12:07:00 +08:00
楼主你先了解一下 markdown code block 再说。
Chares
2021-07-25 20:52:55 +08:00
@RichXu 看了两眼直接翻到评论区看不下去了
LinusChen
2021-07-26 10:18:44 +08:00
@xingheng 我去学了下 markdown,感觉发现新大陆了,但是帖子删不了只能保持现状了。。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/791165

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX