Jupyter实验室单元中循环内的输入

时间:2019-10-30 23:00:30

标签: python jupyter-notebook jupyter-lab

我正在运行Jupyter实验室笔记本 我有一个名称列表,我希望能够输入一些有关列表中每个项目之间关系的信息。

我的想法通常是遍历for循环,但我不认为在jupyter中可以循环遍历输入。

names = ['alex','tom','james']
relationships = []
for i in names:
    for j in names:
        if j==i:
            continue
        skip = False
        for r in relationships:
            if r[0] == {i,j}:
                skip = True
                break
        if skip == True:
            # print(f'skipping {i,j}')
            continue
        strength = input(f'what is the relationship between {i} and {j}?')
        relationships.append(({i,j},strength))

print(relationships)

如果我在终端中运行它而不在jupyter实验室中运行,这会起作用吗?

1 个答案:

答案 0 :(得分:1)

您可以使用itertools.permutations()进一步简化代码。

示例:

import itertools

names = ['alex','tom','james']

unique = set()
permutations = set(itertools.permutations(names, 2))

for pair in permutations:
    if pair not in unique and pair[::-1] not in unique:
        unique.add(pair)

relationships = []

for pair in unique:
    strength = input(f'what is the relationship between {pair[0]} and {pair[1]}?')
    relationships.append((pair,strength))

print(relationships)

控制台输出:

what is the relationship between alex and james?12
what is the relationship between alex and tom?5
what is the relationship between james and tom?6
[(('alex', 'james'), '12'), (('alex', 'tom'), '5'), (('james', 'tom'), '6')]

但是,即使您的代码在jupyter笔记本中似乎也能正常工作:

enter image description here

您也许可以尝试重新启动python内核,即在菜单中转到Kernal-> Restart and Run all。


相关问题:

How to give jupyter cell standard input in python?