![](/img/trans.png)
[英]Jupyter notebook on EMR not printing output while code is running Pyspark
[英]While printing out words that start with 's',my jupyter notebook is not responding is that the code error or notebook problem?
在運行代碼以's'開頭的單詞的打印過程中,jupyter筆記本沒有響應
st = 'Print only the words that start with s in this s'
lis=st.split()
i=0
res=[]
while i<len(lis):
if lis[i][0]=='s':
res.append(list[i])
i+=1
print(res)
如果列表中的第一個單詞不是以s開頭,則您的代碼將卡住,將i的增量更改為if,如下所示:
st = 'Print only the words that start with s in this s'
lis=st.split()
i=0
res=[]
while i<len(lis):
if lis[i][0]=='s':
res.append(list[i])
i+=1
print(res)
編輯:此代碼的改進的版本
st = 'Print only the words that start with s in this s'
res=[]
for s in st.split():
if s[0] == 's':
res.append(s)
print(res)
您還可以使用列表理解
st = 'Print only the words that start with s in this s'
res = [s for s in st.split() if s[0] == 's']
print(res)
# prints ['start', 's', 's']
您可以像下面這樣以更Python的方式嘗試它:
st = 'Print only the words that start with s in this s'
lis=st.split()
results = []
for word in lis:
if word.startswith("s"):
results.append(word)
print(results)
O / P:
['start', 's', 's']
在這種情況下,for循環更好。 拆分字符串時,將獲得單詞列表。 使用for代替while。
st = 'Print only the words that start with s in this s'
lis=st.split()
res=[]
for word in lis:
if(word.startswith("s")):
res.append(word)
您正在使用i
來跟蹤計數( i=0
)和可迭代變量( if lis[i][0]=='s'
)
我建議使用枚舉來跟蹤計數
st = 'Print only the words that start with s in this s'
lis=st.split()
res=[]
for c, i in enumerate(lis):
if i[0] == 's': # here, you can also use i[0].lower() if you want to count words that might start with a capital 's'
res.append(i)
print(c) # keep track of the number of things being iterated over
print(res) # the list of items starting with s
print(len(res)) # how many items starting with s
編輯:在問題編輯之前回答。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.