找到关于如何检查字符串列表是否在一行内的这个很好的答案如何检查 一行是否有列表中的一个字符串?
但是尝试用dict中的键做类似的事情似乎并不适合我:
import urllib2
url_info = urllib2.urlopen('http://rss.timegenie.com/forex.xml')
currencies = {"DKK": [], "SEK": []}
print currencies.keys()
testCounter = 0
for line in url_info:
if any(countryCode in line for countryCode in currencies.keys()):
testCounter += 1
if "DKK" in line or "SEK" in line:
print line
print "testCounter is %i and should be 2 - if not debug the code" % (testCounter)
Run Code Online (Sandbox Code Playgroud)
输出:
['SEK', 'DKK']
<code>DKK</code>
<code>SEK</code>
testCounter is 377 and should be 2 - if not debug the code
Run Code Online (Sandbox Code Playgroud)
想想也许我的问题是因为.keys() …
我想计算python中几个列表的平均值。这些列表包含数字作为字符串。空字符串不是零,它意味着缺少值。
我能想到的最好的就是这个。有没有更优雅,简洁和有效的方式来写这个?
num = ['1', '2', '', '6']
total = sum([int(n) if n else 0 for n in num])
length = sum([1 if n else 0 for n in num])
ave = float(total)/length if length > 0 else '-'
Run Code Online (Sandbox Code Playgroud)
PS 我正在使用 Python 2.7.x 但欢迎使用 Python 3.x 的食谱
对于像 的列表['A', 'B', 'C'],我试图构建或找到一个函数,该函数将在每次调用时返回列表的下一个元素。在这种情况下,如果它被调用超过 3 次,A则将被返回。在那之后B等等。
我有一个['A', 'B', 'C']要应用于不同对象的颜色列表。每次运行代码时,对象的数量可能会有所不同。如果列表中的对象多于颜色,我希望第四个对象具有 color 'A'。所以,正如标题所说,我想遍历一个列表 by 和 index 并从头开始 if index > len(list)。以下自定义函数looper将做到这一点。
def looper(lst, runs):
j = 0
for i in range(0, (len(lst)+(runs-(len(lst))))):
if i < len(lst):
print(lst[i])
else:
print(lst[j])
j +=1
Run Code Online (Sandbox Code Playgroud)
# input:
runs = 2
looper(['A', 'B', 'C'], runs)
# output:
A
B
Run Code Online (Sandbox Code Playgroud)
#input :
runs = 5
looper(['A', 'B', 'C'], runs)
#output …Run Code Online (Sandbox Code Playgroud) 我使用此代码将所有数字相加到 1000,它们是 3 或 5 的倍数。这在技术上是一种列表理解方法吗?
print(sum(i for i in range(1,1000) if i % 3 == 0 or i % 5== 0))
Run Code Online (Sandbox Code Playgroud)