testpachong
V2EX  ›  问与答

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

  •  
  •   testpachong · Jul 20, 2016 · 3334 views
    This topic created in 3616 days ago, the information mentioned may be changed or developed.

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

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

    Supplement 1  ·  Jul 21, 2016
    谢谢各位指点,
    大概就是这样。
    if get_int ==0 or get_int :
    'subject':title[get_int].encode(encoding='gbk'),
    14 replies    2016-07-21 12:13:30 +08:00
    Ziya
        1
    Ziya  
       Jul 20, 2016
    把 post 的内容建个字典,每次 if 的时候修改一下要改变的值
    wlsnx
        2
    wlsnx  
       Jul 20, 2016
    'subject':title[get_int].encode(encoding='gbk'),
    testpachong
        3
    testpachong  
    OP
       Jul 20, 2016
    @wlsnx 这个跟我指定有什么区别吗?
    testpachong
        4
    testpachong  
    OP
       Jul 20, 2016
    @Ziya 给个代码吧,没什么经验
    wlsnx
        5
    wlsnx  
       Jul 20, 2016
    @testpachong 你不是要精简代码吗
    testpachong
        6
    testpachong  
    OP
       Jul 20, 2016
    @wlsnx ...。。。我还需要他能像上面代码那样运行啊
    mgna17
        7
    mgna17  
       Jul 20, 2016
    也许是要这样么

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

    if condition0:
       post.update(c=3)

    if condition1:
       post.update(d=4)
    lxy
        8
    lxy  
       Jul 20, 2016
    看起来像是刚开始学习编程的……
    Leafove
        9
    Leafove  
       Jul 20, 2016
    一般这像是学校里老是举的反面例子...
    Leafove
        10
    Leafove  
       Jul 20, 2016
    打错字了..抱歉
    xujinkai
        11
    xujinkai  
       Jul 20, 2016
    如果变化的只是 title 和 content ,可以直接 title[get_int]和 content[get_int];
    还有一种方法是写一个 post_list = {0: {...}, 1: {...}, ...},然后 post = post_list[get_int];
    总之大段的 if else 不是个好主意
    vimffs
        12
    vimffs  
       Jul 21, 2016
    其实,@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
        13
    wlsnx  
       Jul 21, 2016
    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
        14
    testpachong  
    OP
       Jul 21, 2016
    @wlsnx 我需要让他永远是 true ,我只给了部分代码,不是完整代码。
    总之谢谢。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2783 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 09:57 · PVG 17:57 · LAX 02:57 · JFK 05:57
    ♥ Do have faith in what you're doing.