将变量添加到python结果

时间:2020-04-13 13:30:50

标签: python python-3.x

       if let item = extensionContext?.inputItems.first as? NSExtensionItem,
                let itemProvider = item.attachments?.first as? NSItemProvider,
                itemProvider.hasItemConformingToTypeIdentifier("public.url") {
                itemProvider.loadItem(forTypeIdentifier: "public.url", options: nil) { (url, error) in
                    if let shareURL = url as? URL {
                        // do what you want to do with shareURL
                        print(shareURL)
                        self.shareURL = shareURL
                    }
                }
            }

我需要将结果from random import randint while True: list1 = [] list2 = [] zero = 0 one = 0 sec = int(input("Enter a number seconds : ")) if sec < 0 or sec == 0: break random = randint(0, 2 ** sec - 1) bin_key_one = f'{random:0{int(sec)}b}' for x in bin_key_one: list1.append(x) for i in list1: if i == '0': zero = zero + 1 elif i == '1': one = one + 1 if zero - one < 0: list2.append("backward") elif zero - one > 0: list2.append("forward") elif zero - one == 0: list2.append("No moves") print("The Final position ", zero - one, list2, "steps", end=" ") print("The random number = ", random, end=" ") print("to binary = ", bin_key_one) list1 = [] list2 = [] zero = 0 one = 0 保留在结果中,但是当我将它们放入结果中时,每次需要添加一个变量使其起作用时,结果都为zero - one

1 个答案:

答案 0 :(得分:0)

使用“保持零一的结果”,我想你的意思是您输入到list2中的值。在这种情况下,您需要将list2放在循环之外:

from random import randint

list2 = []

while True:
    list1 = []
    zero = 0
    one = 0
    sec = int(input("Enter a number seconds : "))
    if sec < 0 or sec == 0:
        break
    random = randint(0, 2 ** sec - 1)
    bin_key_one = f'{random:0{int(sec)}b}'
    for x in bin_key_one:
        list1.append(x)
    for i in list1:
        if i == '0':
            zero = zero + 1
        elif i == '1':
            one = one + 1
    if zero - one < 0:
        list2.append("backward")
    elif zero - one > 0:
        list2.append("forward")
    elif zero - one == 0:
        list2.append("No moves")6

    print("The Final position  ", zero - one, list2, "steps", end=" ")
    print("The random number = ", random, end=" ")
    print("to binary = ", bin_key_one)

for i in list2:
    print(i)

这是结果

Enter a number seconds : 6
The Final position   0 ['No moves'] steps The random number =  28 to binary =  011100
Enter a number seconds : 4
The Final position   2 ['No moves', 'forward'] steps The random number =  8 to binary =  1000
Enter a number seconds : 2
The Final position   0 ['No moves', 'forward', 'No moves'] steps The random number =  1 to binary =  01
Enter a number seconds : 0
No moves
forward
No moves