所以我的目标是从:
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方式吗?
我试图做一个更优雅的代码版本.这基本上只是根据数字将字符串附加到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) 如果你有三个列表,这是最简单的方法
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中完成这项工作
如果你有字符串"'a','b'"- >因为list("'a','b'")它被转换为["'", 'a', "'", ',', "'", 'b', "'"]但我希望它像:['a', 'b']
例如:
a = 'a','b' -> list(a) -> ['a', 'b']
Run Code Online (Sandbox Code Playgroud) 例如,如果我有代码:
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(自我)?
这类似于方法重载。当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)