簡體   English   中英

如何將打印 output 分配給變量

[英]How to assign print output to a variable

moleculeparse = chemparse.parse_formula(molecule) #Parses the molecular formula to present the atoms and No. of atoms. Molecule here is 'C2H6O2' 
print(moleculeparse) #Print the dictionary

for x,y in moleculeparse.items(): #For every key and value in dictionary
    y = numpy.random.randint(0,y+1) #Randomly generate the value between 0 and y+1
    if y == 0:
        continue
    else:
        y = str(y)
        print(x+y, end = "")

上面的代碼本質上是解析“C2H6O”並將其放入字典中。 然后對於字典中的每個鍵和值,隨機生成值。

運行此代碼時,output 的示例可以是諸如“C1H4”之類的內容,這就是最后一行中的打印語句所做的。 我希望能夠將此 output 分配給一個變量以供以后使用,但我不確定如何執行此操作。 我已經分配了嘗試a = x+y, end = ""但這會導致錯誤。 任何幫助,將不勝感激

這應該是對的

moleculeparse = chemparse.parse_formula(molecule) #Parses the molecular formula to present the atoms and No. of atoms. Molecule here is 'C2H6O2' 
print(moleculeparse) #Print the dictionary

for x,y in moleculeparse.items(): #For every key and value in dictionary
    y = numpy.random.randint(0,y+1) #Randomly generate the value between 0 and y+1
    if y == 0:
        continue
    else:
        y = str(y)
        a = x+y
        print(a, end = "")

最簡單的方法是將每個結果保存在一個列表中,然后將其整理成一個字符串。 您不想“將打印 output 分配給變量”:不需要打印每個結果。

moleculeparse = chemparse.parse_formula(molecule) #Parses the molecular formula to present the atoms and No. of atoms. Molecule here is 'C2H6O2' 
print(moleculeparse) #Print the dictionary

all_results = []

for x, y in moleculeparse.items():  # For every key in dictionary
    y = numpy.random.randint(0,y+1)  # Randomly generate the value between 0 and y+1
    if y == 0:
        continue
    else:
        y = str(y)
        all_results.append(x+y)
in_one_line = "".join(all_results)
print(in_one_line)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM