小编use*_*339的帖子

"扁平化"词典列表

所以我的目标是从:

fruitColourMapping = [{'apple': 'red'}, {'banana': 'yellow'}]
Run Code Online (Sandbox Code Playgroud)

finalMap = {'apple': 'red', 'banana': 'yellow'}
Run Code Online (Sandbox Code Playgroud)

我得到的方法是:

 from itertools import chain
 fruits = list(chain.from_iterable([d.keys() for d in fruitColourMapping]))
 colour = list(chain.from_iterable([d.values() for d in fruitColourMapping]))
 return dict(zip(fruits, colour))
Run Code Online (Sandbox Code Playgroud)

还有更好的pythonic方式吗?

python dictionary

20
推荐指数
8
解决办法
2万
查看次数

如果在python中附加到数组,如何更优雅地执行elif语句

我试图做一个更优雅的代码版本.这基本上只是根据数字将字符串附加到categorynumber.非常感谢任何帮助.

number = [100,150,200,500] 
categoryNumber = []

for i in range (0,len(number)):
    if (number [i] >=1000):
        categoryNumber.append('number > 1000')
    elif (number [i] >=200):
        categoryNumber.append('200 < number < 300')
    elif (number [i] >=100):
        categoryNumber.append('100 < number < 200')
    elif (number [i] >=50):
        categoryNumber.append('50 < number < 100')      
    elif (number [i] < 50):
        categoryNumber.append('number < 50')

for i in range(0,len(categoryNumber)):
    print i
Run Code Online (Sandbox Code Playgroud)

python loops

9
推荐指数
1
解决办法
300
查看次数

映射字典和列表python

如果你有三个列表,这是最简单的方法

list [1,2,3] [a,b,c] [5,6,7]
Run Code Online (Sandbox Code Playgroud)

用字典映射它

{1:{'a':5}, 2:{'b':6}, 3:{'c':7}} 
Run Code Online (Sandbox Code Playgroud)

有一种感觉你必须使用拉链..

如何在没有字典理解的python中完成这项工作

python dictionary list

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

在python中将字符串转换为数组

如果你有字符串"'a','b'"- >因为list("'a','b'")它被转换为["'", 'a', "'", ',', "'", 'b', "'"]但我希望它像:['a', 'b']

例如:

a = 'a','b' -> list(a) -> ['a', 'b']
Run Code Online (Sandbox Code Playgroud)

python list

0
推荐指数
1
解决办法
110
查看次数

在python中写if else的更优雅方式

例如,如果我有代码:

class Example ():

    def a(self):
        return 'Buy'

    def b(self):
        if (self.a() == 'Buy'):
            return 'BUY SET'
        elif (self.a() == 'Sell'):
            return 'SELL SET''

o = Example()
value = o.b()   
print value 
Run Code Online (Sandbox Code Playgroud)

是否有更优雅/ pythonic的方式我可以写函数b(自我)?

python coding-style

0
推荐指数
1
解决办法
1574
查看次数

方法重载Python

这类似于方法重载。当print Hello(1, 2, 3)执行时它会返回"a and b",而我希望它返回"a and b and c"。我知道我可以说if (a and b and c is None)这样就会有效。但是,如果我有 20 个参数并且我必须处理每种情况,那么这将只是多个if我认为没有必要的语句。我应该有更好的方法来解决这样的问题吗?

 def Hello(a=None, b=None, c=None):
    if(a and b):
        return "a and b"
    if(a and c):
       return "a and c"
    if(a and b and c):
       return "a and b and c"

print Hello(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

python operator-overloading

0
推荐指数
1
解决办法
202
查看次数