这段代码怎么精简啊,看着太蛋疼了

2016-07-20 15:59:47 +08:00
 testpachong

代码这这里: http://pastebin.com/N30GhaJS

或者这里: http://pastie.org/10912748

2580 次点击
所在节点    问与答
14 条回复
Ziya
2016-07-20 16:05:55 +08:00
把 post 的内容建个字典,每次 if 的时候修改一下要改变的值
wlsnx
2016-07-20 16:07:03 +08:00
'subject':title[get_int].encode(encoding='gbk'),
testpachong
2016-07-20 17:00:36 +08:00
@wlsnx 这个跟我指定有什么区别吗?
testpachong
2016-07-20 17:00:51 +08:00
@Ziya 给个代码吧,没什么经验
wlsnx
2016-07-20 17:18:14 +08:00
@testpachong 你不是要精简代码吗
testpachong
2016-07-20 17:19:36 +08:00
@wlsnx ...。。。我还需要他能像上面代码那样运行啊
mgna17
2016-07-20 17:29:04 +08:00
也许是要这样么

post = {
    'a': 1,
    'b': 2}

if condition0:
   post.update(c=3)

if condition1:
   post.update(d=4)
lxy
2016-07-20 17:32:13 +08:00
看起来像是刚开始学习编程的……
Leafove
2016-07-20 17:47:44 +08:00
一般这像是学校里老是举的反面例子...
Leafove
2016-07-20 17:48:05 +08:00
打错字了..抱歉
xujinkai
2016-07-20 20:26:50 +08:00
如果变化的只是 title 和 content ,可以直接 title[get_int]和 content[get_int];
还有一种方法是写一个 post_list = {0: {...}, 1: {...}, ...},然后 post = post_list[get_int];
总之大段的 if else 不是个好主意
vimffs
2016-07-21 10:55:31 +08:00
其实,@wlsnx 已经指出了,只是 OP 没看懂?

给出的代码可用下面的替换:
```
get_int = random.randint(0, 3)
post = {
'formhash':formhash_code,
'wysiwyg':'0',
'iconid':'',
'updateswfattach':'0',
'subject':title[get_int].encode(encoding='gbk'),
'checkbox':'0',
'message':content[get_int].encode(encoding='gbk'),
'attachdesc[]':'',
'localid[]':'',
'attachperm[]':'0',
'attachprice[]':'0',
'attachdesc[]':'',
'localid[]':'1',
'attachperm[]':'0',
'attachprice[]':'0',
'readperm':'',
'price':'',
}
```
wlsnx
2016-07-21 12:01:23 +08:00
if get_int ==0 or get_int : 这句可以去掉
如果 get_int 是个数字, get_int ==0 or get_int 永远是 True
数字 x 的 __nonzero__ 为 True 的条件是 x != 0
if get_int ==0 or get_int 相当于 if get_int == 0 or get_int != 0
testpachong
2016-07-21 12:13:30 +08:00
@wlsnx 我需要让他永远是 true ,我只给了部分代码,不是完整代码。
总之谢谢。

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

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

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

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

© 2021 V2EX