【问题标题】:Inputs within loop in jupyter lab celljupyter实验室单元中循环内的输入
【发布时间】:2019-10-30 23:00:30
【问题描述】:

我正在运行一个 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 实验室中运行它,这会起作用,什么可能起作用?

【问题讨论】:

  • 我在 jupyter 中运行了你的代码,最后得到了 [({'alex', 'tom'}, 'good'), ({'alex', 'james'}, 'bad' ), ({'james', 'tom'}, 'nice')]。这不是你所期待的吗?也许发布你的细胞的样子。

标签: python jupyter-notebook jupyter-lab


【解决方案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 notebook 中似乎也可以正常工作:

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


相关问题:

How to give jupyter cell standard input in python?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多