Python 3.x 使用Python打印一个列表,其中值彼此之间的距离特定
我有一份清单Python 3.x 使用Python打印一个列表,其中值彼此之间的距离特定,python-3.x,Python 3.x,我有一份清单 A = ['A','B','C','D','E','F','G','H'] 如果用户输入x=4,那么我需要一个输出,显示彼此之间距离为4的每个值。 如果在打印距离为4的值(即:{'A','E'})之后从'A'开始,则代码应往回迭代,并从'B'开始打印所有值,即:{'B','F'} 号码不能在多个组中 任何帮助都将受到感谢,因为我对python非常陌生 这就是我所做的 x = input("enter the number to divide with: ") A = ['A','
A = ['A','B','C','D','E','F','G','H']
如果用户输入x=4
,那么我需要一个输出,显示彼此之间距离为4的每个值。
如果在打印距离为4的值(即:{'A','E'})之后从'A'开始,则代码应往回迭代,并从'B'开始打印所有值,即:{'B','F'}
号码不能在多个组中
任何帮助都将受到感谢,因为我对python非常陌生
这就是我所做的
x = input("enter the number to divide with: ")
A = ['A','B','C','D','E','F','G','H']
print("Team A is divided by " +x+ " groups")
print("---------------------")
out = [A[i] for i in range(0, len(A), int(x))]
print(out)
当用户输入x=4时,我的代码仅打印以下内容
{'A', 'E'}
但我需要它看起来像下面这样
{'A', 'E'}
{'B', 'F'}
{'C', 'G'}
{'D', 'H'}
我做错了什么?使用zip
:
out = list(zip(A, A[x:]))
例如:
x = 4 # int(input("enter the number to divide with: "))
A = ['A','B','C','D','E','F','G','H']
print(f"Team A is divided by {x} groups")
print("---------------------")
out = list(zip(A, A[x:]))
print(out)
产出:
[('A', 'E'), ('B', 'F'), ('C', 'G'), ('D', 'H')]
给你钱
如果你想保持理解力:
out = [(A[i], A[i+x]) for i in range(0, len(A)-x)]
**你可以在下面找到我的答案
def goutham(alist):
for passchar in range(0,len(alist)-4):
i = alist[passchar]
j = alist[passchar+4]
print("{"+i+","+j+"}")
j = 0
alist = ['a','b','c','d','e','f','g','h']
goutham(alist)