What is idiomatic code?

后端 未结 5 906
时光说笑
时光说笑 2020-12-07 14:22

I\'d be interested in some before-and-after c# examples, some non-idiomatic vs idiomatic examples. Non-c# examples would be fine as well if they get the idea across. Thanks.

5条回答
  •  庸人自扰
    2020-12-07 15:17

    Idiomatic means following the conventions of the language. You want to find the easiest and most common ways of accomplishing a task rather than porting your knowledge from a different language.

    non-idiomatic python using a loop with append:

    mylist = [1, 2, 3, 4]
    newlist = []
    for i in mylist:
        newlist.append(i * 2)
    

    idiomatic python using a list comprehension:

    mylist = [1, 2, 3, 4]
    newlist = [(i * 2) for i in mylist] 
    

提交回复
热议问题