[英]How can I convert for loop into .apply?
我正在解決算法問題,我想知道我是否可以將這個 for 循環轉換為.apply。 但我不知道該怎么做。 這是我的代碼:
# Let's use .apply
import pandas as pd
class Solution:
def longestCommonPrefix(self, strs: list[str]) -> str:
result = ""
for i in range(len(strs[0])):
for s in strs:
if i == len(s) or s[i] != strs[0][i]:
return result
result += strs[0][i]
return result
strs = ['flower','flow','flight']
df = pd.DataFrame([strs])
df
Solution().longestCommonPrefix(df.iloc[0])
這是 output:
'fl'
它基本上是返回最長公共前綴的算法。
你當然可以。 請參考以下例子。 我在這里冒昧地重構了您的代碼,使其更加簡潔並有利於.apply
方法,並添加了一些文檔。
例如:
import pandas as pd
def longestprefix(s: pd.Series) -> str:
"""Determine the longest prefix in a collection of words.
Args:
s (pd.Series): A pandas Series containing words to be analysed.
Returns:
str: The longest common series of characters, from the beginning.
"""
result = ''
for chars in zip(*s):
# Test that all characters are the same.
if all(chars[0] == c for c in chars[1:]):
result += chars[0]
else: break
return result
# Create a DataFrame containing strings to be analysed.
df = pd.DataFrame(data=['flower','flow','flight', 'flows'])
# Apply the function to each *column*. (i.e. axis=0)
df.apply(longestprefix, axis=0)
Output:
0 fl
dtype: object
要獲取單個字符串,您可以使用:
>>> df.apply(longestprefix, axis=0).iloc[0]
'fl'
根據評論,進一步描述為什么使用zip(*s)
:
zip
function 使 Series 中每個單詞的第 n 個字母一起打包成一個元組。 換句話說,它讓我們比較所有的第一個字母,所有的第二個字母,等等。為了演示,鍵入list(zip(*df[0]))
(其中0
是列名)以顯示正在檢查的項目迭代。 如果您直接迭代系列,您只是迭代單個單詞,而不是第 n 個字母的元組。
例如:
[('f', 'f', 'f', 'f'), # <-- These are the values being compared.
('l', 'l', 'l', 'l'),
('o', 'o', 'i', 'o'),
('w', 'w', 'g', 'w')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.