小编Ari*_*ian的帖子

Python,我在循环中重复了很多,必须有更好的方法

假设我有三个列表,我需要遍历它们并对内容做一些事情.

这三个名单streaks_0,streaks_1streaks_2.对于每个列表,我需要使用特定于每个列表的不同值.例如,streak_0_num0sstreaks_1for循环中不起作用.

有没有办法让这三个for循环成为一个或至少一种方法来清理它?

for number in streaks_0:
    if number == 0:
        streak_0_num0s += 1
    elif number != 0:
        streak_0_sum += number
streak_0_average = (streak_0_sum / (len(streaks_0) - streak_0_num0s))

for number in streaks_1:
    if number == 0:
        streak_1_num0s += 1
    elif number != 0:
        streak_1_sum += number
streak_1_average = (streak_1_sum / (len(streaks_1) - streak_1_num0s))

for number in streaks_2:
    if number == 0:
        streak_2_num0s += 1
    elif number != 0:
        streak_2_sum += …
Run Code Online (Sandbox Code Playgroud)

python for-loop dry

11
推荐指数
4
解决办法
879
查看次数

Python Matplotlib 如何仅获取表格

我修改了示例代码并使表格按照我想要的方式工作,但是,仍然有一个框,图表将位于表格下方。我想摆脱那个盒子。请注意,该表有 5 行(包括列标签)和 8 列(包括行标签)。

相关代码:

columns = ('Last', 'High', 'Low', 'Chg.', 'Chg. %', 'Time', 'T?')
rows = ['Gold', 'Silver', 'Copper', 'Aluminum']
scatter_x = (1, 2, 3)
scatter_y = (1224.53, 1231.76, 1228.70)
fig = plt.figure(1)
gridspec.GridSpec(4,3)

#Table - Main table
plt.subplot2grid((4,3), (0,0), colspan=2, rowspan=2)
plt.table(cellText=data_list,
          rowLabels=rows,
          colLabels=columns,
          loc='top')
plt.subplots_adjust(left=0.2,top=0.8)
plt.yticks([])
plt.xticks([])

#Gold Scatter - Small scatter to the right
plt.subplot2grid((4,3), (0,2))
plt.scatter(scatter_x, scatter_y)
plt.ylabel('Gold Last')


fig.tight_layout()
fig.set_size_inches(w=6, h=5)
fig_name = 'plot.png'
fig.savefig(fig_name)
plt.show()
Run Code Online (Sandbox Code Playgroud)

它产生了这个: 查看表格下方的空方块

一个问题:我如何将填充设置在桌子上,使其不会在顶部和左侧被切断?

python matplotlib

4
推荐指数
1
解决办法
8389
查看次数

如何使用密码模块加密变量?

我不确定是否有人熟悉加密模块,但是我正在尝试加密代表字符串的变量。

例如:

string = input('String here')
Run Code Online (Sandbox Code Playgroud)

他们在模块页面上给出的示例是:

from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
cipher_text = cipher_suite.encrypt(b"A really secret message. Not for prying eyes.")
plain_text = cipher_suite.decrypt(cipher_text)
Run Code Online (Sandbox Code Playgroud)

一切都很好,但是当我尝试用一​​个变量替换“真正的秘密消息字符串”时,它不起作用。

如果用引号引起来,则只打印变量的名称(duh)

如果没有这样的引号:cipher_text = cipher_suite.encrypt(bstring),则表示未定义变量(也是duh)

但是,如果我只是将变量放入,它将给我一个错误: TypeError: data must be bytes.

有任何想法吗?谢谢!

python encryption cryptography module

2
推荐指数
1
解决办法
2744
查看次数

标签 统计

python ×3

cryptography ×1

dry ×1

encryption ×1

for-loop ×1

matplotlib ×1

module ×1