我有这样的不同行如何将这些行作为pep8兼容?
messbycircle_freq_result['percentage']=
messbycircle_freq_result['smstext']/sum(messbycircle_freq_result['smstext'])
错误1:行太长
错误2:意外缩进
并且还面临着如下许多问题
buckets = np.where(tobebuckets< = 0,0, np.where(np.logical_and(tobebuckets大于0, tobebuckets< = 10),10,np.where(np.logical_and(tobebuckets> 10,tobebuckets< = 50), 50,np.where(np.logical_and(tobebuckets> 50,tobebuckets< = 100),100,np.where(np.logical_and(tobebuckets> 100,tobebuckets< = 500),500,np.where(np.logical_and( tobebuckets> 500,tobebuckets< = 1000),1000,1001))))))
请帮助我填写上面的代码,就像之前的代码一样。非常感谢你早些时候。
答案 0 :(得分:2)
(
messbycircle_freq_result['percentage'] =
messbycircle_freq_result['smstext'] /
sum(messbycircle_freq_result['smstext'])
)
基本上你需要保留所有小于80个字符的行。
所以你有更多的方法可以做到这一点,
messbycircle_freq_result['percentage'] = (
messbycircle_freq_result['smstext'] /
sum(messbycircle_freq_result['smstext'])
)
等
答案 1 :(得分:1)
def calculate_percentage(result):
result['percentage'] = result['smstext'] / sum(result['smstext'])
calculate_percentage(messbycircle_freq_result)
答案 2 :(得分:0)
嵌入这么多电话并保持在80个字符以下是不容易的,为什么不将它们分解(要保持80个字符以下你仍然需要分割线路):
buckets1000 = np.where(np.logical_and(tobebuckets > 500, tobebuckets <= 1000),
1000, 1001)
buckets500 = np.where(np.logical_and(tobebuckets > 100, tobebuckets <= 500),
500, buckets1000)
buckets100 = np.where(np.logical_and(tobebuckets > 50, tobebuckets <= 100),
100, buckets500)
buckets50 = np.where(np.logical_and(tobebuckets > 10, tobebuckets <= 50),
50, buckets100)
buckets10 = np.where(np.logical_and(tobebuckets > 0, tobebuckets <= 10),
10, buckets50)
buckets = np.where(tobebuckets <= 0, 0, buckets10)
或者你可以强迫它在一行:
buckets = np.where(
tobebuckets <= 0, 0,
np.where(
np.logical_and(tobebuckets > 0, tobebuckets <= 10), 10,
np.where(
np.logical_and(tobebuckets > 10,tobebuckets <= 50), 50,
np.where(
np.logical_and(tobebuckets > 50, tobebuckets <= 100), 100,
np.where(
np.logical_and(tobebuckets > 100, tobebuckets <= 500), 500,
np.where(
np.logical_and(tobebuckets > 500, tobebuckets <= 1000),
1000, 1001))))))
这些都不是极具吸引力的代码。
您可以将where子句抽象为递归函数:
def where(s, l):
if not l:
return s+1
return np.where(np.logical_and(tobebuckets > s, tobebuckets <= l[0]),
l[0], where(l[0], l[1:]))
buckets = np.where(tobebuckets <= 0, 0, where(0, [10, 50, 100, 500, 1000]))
答案 3 :(得分:0)
简短的便利变量 - 在狭义的代码部分中战略性地使用 - 可以创造奇迹来减少视觉过载,从而提高可读性,同时不会牺牲清晰度。
这个例子说明了这个想法,并以achampion的答案为基础。
mfr = messbycircle_freq_result
mfr['percentage'] = mfr['smstext'] / sum(mfr['smstext'])
tbb = tobebuckets
bs1000 = np.where(np.logical_and(tbb > 500, tbb <= 1000), 1000, 1001)
bs500 = np.where(np.logical_and(tbb > 100, tbb <= 500), 500, bs1000)
bs100 = np.where(np.logical_and(tbb > 50, tbb <= 100), 100, bs500)
bs50 = np.where(np.logical_and(tbb > 10, tbb <= 50), 50, bs100)
bs10 = np.where(np.logical_and(tbb > 0, tbb <= 10), 10, bs50)
buckets = np.where(tbb <= 0, 0, bs10)