我試圖在陣列中找到一個包含“橙色”的單詞。它有效,但是當我添加 else 陳述句以顯示訊息“未找到匹配項”時,我得到了這個結果。
matches not found
x-orange-test
orange
new_orange
matches not found
我究竟做錯了什么?如果陣列中存在“橙色”,為什么會出現“未找到匹配項”訊息?
邏輯是這樣的:如果陣列中至少有一個元素帶有“橙色”一詞,則只列印這些元素。如果陣列不包含帶有“橙色”一詞的元素,則列印一行“未找到匹配項”,對不起,我是 LUA 的新手。我的代碼。
local items = { 'apple', 'x-orange-test', 'orange', 'new_orange', 'banana' }
for key,value in pairs(items) do
if string.match(value, 'orange') then
print (value)
else
print ('matches not found')
end
end
相當于Python代碼,對找到的元素的總和進行了輕微修正。它按我需要的方式作業。但我需要弄清楚如何在 LUA 中做同樣的事情
#!/usr/bin/env python3
items = ['apple', 'x-orange-test', 'orange', 'new_orange', 'banana']
if any("orange" in s for s in items):
sum_orange = sum("orange" in s for s in items)
print (sum_orange)
else:
print('matches not found')
提前致謝。
uj5u.com熱心網友回復:
您的 lua 代碼會列印表中每個元素的結果,因此您將收到兩次“未找到”訊息,因為確實有兩個元素沒有橙色。
您的 Python 代碼使用完全不同的邏輯,無法與 lua 代碼進行比較。要修復 lua 代碼,您可以使用以下代碼:
found = false
for key,value in pairs(items) do
if string.match(value, 'orange') then
print (value)
found = true
end
end
if not found then
print ('matches not found')
end
uj5u.com熱心網友回復:
對于第一個代碼,您將遍歷集合中的每個專案并檢查專案中是否包含“橙色”。因此,當您到達不包含單詞“orange”的專案時,else 條件為真,因此會列印未找到的匹配項。我建議您從 for 回圈中洗掉 print('matches not found') 。而是創建一個布林值來檢查是否在集合中的任何專案中找到“橙色”。在 for 回圈之外,您可以檢查布林值是否為假,然后列印“未找到匹配”。請看下面的代碼:
local items = { 'apple', 'x-orange-test', 'orange', 'new_orange', 'banana' }
local matchFound = false
for key,value in pairs(items) do
if string.match(value, 'orange') then
print (value)
matchFound = true
end
end
if not matchFound then
print('matches not found')
uj5u.com熱心網友回復:
你可以像這樣匹配迭代器。
-- table method extend
---@param t string[]
---@param value string
function table.find(t, value)
if type(t) ~= "table" or t[1] == nil then
error("is not a array")
return
end
for k, v in ipairs(t) do
if v == value then
return true, t[k]
end
end
return false, nil
end
local items = {
"apple",
"x-orange-test",
"orange",
"new_orange",
"banana"
}
print(table.find(items, "orange"))
--> true orange
print(table.find(items, "orange-odd"))
--> false nil
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/441209.html
標籤:Python python-3.x 列表 lua lua 表
