jupyter 实验室单元中循环内的输入
Inputs within loop in jupyter lab cell
我正在 运行使用 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 实验室中不可用,这会起作用,什么可能起作用?
您可以使用 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 内核,即在菜单中转到内核 -> 重新启动和 运行 全部。
相关问题:
我正在 运行使用 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 实验室中不可用,这会起作用,什么可能起作用?
您可以使用 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 内核,即在菜单中转到内核 -> 重新启动和 运行 全部。
相关问题: