【问题标题】:Can I get a code review? Need help if I could have done this more efficient [closed]我可以获得代码审查吗?如果我可以更有效地做到这一点,需要帮助[关闭]
【发布时间】:2018-12-02 09:51:24
【问题描述】:

我是新来的,并且是使用 python 编码的新手。我最近开始了一个在线粗略,想看看是否有更简单的方法可以创建一个 12 位随机十六进制列表。我希望每个单独的位都是小写或大写的随机数或字母。根据我的菜鸟研究,这是我能找到的最好的并创建了我自己的代码.. 那么我可以做得更简单有效吗?

#!/user/bin/python
import string
import random 

r1 = random.choice(string.hexdigits)
r2 = random.choice(string.hexdigits) 
r3 = random.choice(string.hexdigits)  
r4 = random.choice(string.hexdigits) 
r5 = random.choice(string.hexdigits)
r6 = random.choice(string.hexdigits)
r7 = random.choice(string.hexdigits)
r8 = random.choice(string.hexdigits)
r9 = random.choice(string.hexdigits)
r10 = random.choice(string.hexdigits)
r11 = random.choice(string.hexdigits)
r12 = random.choice(string.hexdigits)

randnumb = r1+r2+":"+r3+r4+":"+r5+r6+":"+r7+r8+":"+r9+r10+":"+r11+r12

print(randnumb)

【问题讨论】:

  • 您好,欢迎来到 StackOverflow。供您参考,images of code are highly discourages
  • 请将您的代码发布为文本,而不是图像。此外,如果您的代码已经在工作并且您只想改进它,那么您的问题可能与 SO 无关,并且可能与 Code Review 更相关。

标签: python python-3.x review


【解决方案1】:

您可以使用带有str.join() 的循环:

from random import choice
from string import hexdigits

print(":".join(choice(hexdigits) + choice(hexdigits) for _ in range(6)))
# 47:8b:FA:71:90:ea

将两个随机十六进制数字组合 6 次,相当于您的 12 次单独调用。

或者正如 @Jon Clements 在 cmets 中建议的那样:

':'.join(format(choice(range(256)), 'x') for _ in range(6))

在所有 256 个 ASCII 字符中使用十六进制格式 'x'format()

此外,为了超级安全,您可以使用 02x/02X 将格式填充为 2 个字符:

format(choice(range(256)), '02x') # lowercase padding
format(choice(range(256)), '02X') # uppercase padding

x 是小写十六进制,X 是大写十六进制。最好在这里保持一致以避免奇怪的小写和大写混合。这种一致性的一个例子是 MAC 地址,其中十六进制字符串仅使用小写字母。

您可以在Format Specification Mini-Language 中阅读有关此内容及其变体的更多信息。

您可以做的另一件事是将choice(range(256)) 替换为random.randrange(256),避免使用range()

【讨论】:

  • 或者...':'.join(format(choice(range(256)), 'x') for _ in range(6))...
  • @JonClements 非常好。我把你的答案加进去了。
  • @RoadRunner 嘿,感谢您的帮助。一般来说,我对编码很陌生,我可以理解你建议的代码,但我不知道如何运行它。我只是输入了 3 行,没有任何反应。如果要问的不是太多,您还添加了什么。或者完整的代码是什么
  • @Jbravo 我在解释器中编写的第一个代码片段,我没有添加任何其他内容。如果将第一个示例粘贴进去,它应该可以工作。我不确定你的 python 环境是什么,但我在命令行中使用python <your python script> 运行脚本。
  • 是的...x 用于小写,X 用于大写十六进制数字...保持一致,否则由于string.hexdigits'0123456789abcdefABCDEF',您最终可以得到一个看起来很奇怪(但仍然有效)的字符串,例如:aA:Fe 随机选择时的那种东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-04
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
相关资源
最近更新 更多