Входы внутри цикла в ячейке лаборатории Юпитера - PullRequest
1 голос
/ 31 октября 2019

Я использую лабораторную тетрадь 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 Ответ

1 голос
/ 31 октября 2019

Вы можете еще больше упростить свой код, используя 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 иRun all.


Смежный вопрос:

Как дать стандартный ввод ячейки юпитера в python?

...