编写一个程序,用给定的字符串列表中的整数值替换每个字符串。替换整数值应为相应字符串的每个字符的Ascci值之和。
list_rivers =["Ganges", "Godavari", "Brahmaputra", "Narmada","Yamuna", "Mahanadi", "Kaveri", "Tapti"]
我尝试了以下正确的方法,但是我想优化代码。
list_rivers =["Ganges", "Godavari", "Brahmaputra", "Narmada", "Yamuna", "Mahanadi", "Kaveri", "Tapti"]
river = [] // empty list
for i in list_rivers:
num=0
for j in i:
num = num + ord(j)
river.append(num) // [597, 813, 1143, 692, 619, 787, 610, 514]
任何人都可以帮助优化上述代码吗?
预先感谢。
答案 0 :(得分:1)
您可以使用列表理解:
[sum([ord(i) for i in word]) for word in list_rivers]
等同于
tmp_1 = []
for word in list_rivers:
tmp_2 = []
for i in word:
tmp_2.append(ord(i))
tmp_1.append(sum(tmp_2))
答案 1 :(得分:0)
正如iElden所述,您可以在此处使用列表理解功能。请注意,在这种情况下,这样做不一定会优化代码以提高效率。
您的方法:
%%timeit
river = []
for i in list_rivers:
num=0
for j in i:
num = num + ord(j)
river.append(num)
# 100000 loops, best of 3: 6.57 µs per loop
列表理解:
%%timeit
result = [sum([ord(i) for i in word]) for word in list_rivers]
# 100000 loops, best of 3: 9.37 µs per loop
(甚至更慢)使用地图:
%%timeit
result = map(lambda x: sum([ord(letter) for letter in x]), list_rivers)
# 100000 loops, best of 3: 10.3 µs per loop
答案 2 :(得分:0)
它说编写一个程序来做,所以这里是一个程序。输出示例:[597, 813, 1143, 692, 619, 787, 610, 514]
def string_to_int(string):
retval = 0
for c in string:
retval += ord(c)
return retval
def main(data):
retval = []
for item in data:
retval.append(string_to_int(item))
return retval
if __name__ == "__main__":
list_rivers = ["Ganges", "Godavari", "Brahmaputra", "Narmada", "Yamuna", "Mahanadi", "Kaveri", "Tapti"]
results = main(list_rivers)
print results