作為序言,我對python不是很有經驗。我目前正在嘗試使用我所知道的和我可以使用的工具來學習。
概括
我想創建一個函式,該函式接收字典,然后將所述字典的鍵和值相乘。但是,我想要的外部條件使這個問題變得困難。
這些條件是:
如果其中一個值為負數,則不是將該值乘以它的相應鍵,而是將 x 個星號乘以其中 x 是相應鍵中的字符數量乘以 abs(value)。
該函式只能使用基本的 for/while 回圈和 if 陳述句。通過在線查看類似問題,我對串列理解有些熟悉,但我并不擅長。相反,我想練習使用更簡單的方法。
函式本身應該看起來像 dict_multiply(dict):,并且測驗試驗應該看起來像dict_multiply({'Terra': 6, 'Cloud': -7, 'Squall': 8})回傳'TerraTerraTerraTerraTerraTerra***********************************SquallSquallSquallSquallSquallSquallSquallSquall'。Terra 重復 6 次,“Cloud”中的字母轉換為星號并乘以 abs(-7),Squall 重復 8 次。
我正在嘗試什么
我嘗試做的是將問題分解為步驟。為了方便不必重新運行它,我還沒有將任何代碼放入函式中,但我一直在試驗變數。
例如,我想嘗試創建一個條件,將字典中的負值讀取為星號。
dictionary = {'Terra': 6, 'Cloud': -7, 'Squall': 8}
keylist = list(dictionary.keys())
valuelist = list(dictionary.values())
for values in valuelist:
if values < 0:
valuelist[valuelist.index(values)] = abs(values) * ('*')
valuelist
which returns [6, '*******', 8]. This is only a single component that I want from the function, but I think I'm getting somewhere. keylist is a list containing ['Terra', 'Cloud', 'Squall'] which I want to multiply by the valuelist I returned. I know I can multiply strings such as 'Terra' by int values such as 6, but I know multiplying two strings together such as '*******' and 'Cloud' is impossible. Instead, I would just want the asterisks returned but I'm unsure on how to create this condition.
The issue of actually multiplying the lists of ints by the list of strings is something I'm concerned about too. I've seen explanations for this step online but none of the explanations are at my level of coding (basic for/while loops).
disregarding this and assuming that multiplication somehow succeeds, I think it I should be left with a list of strings separated by commas which I know I can merge into a single string using ''.join(c) (assuming that c is the result of the step I'm having trouble with).
I'm sorry if my thought process may be confusing. I'm still in the process of learning python. Going forward, I want to be able to break down problems like these into steps and determine which steps I should think about first. Any feedback is appreciated.
uj5u.com熱心網友回復:
您可以嘗試運行以下代碼:
def dict_multiply(d: dict):
s = ""
for key, val in d.items():
if val > 0:
s = key * val
else:
s = "*" * abs(val) * len(key)
return s
print(dict_multiply({'Terra': 6, 'Cloud': -7, 'Squall': 8}))
在這里,我們遍歷輸入字典的鍵和值。如果該值大于 0(因此為正),我們將鍵添加值多次。如果不是,我們將星號添加為價值時間的絕對值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/456864.html
