Python 列表的“关于for循环”具有重复的值
我正在尝试为循环创建一个Python 列表的“关于for循环”具有重复的值,python,python-3.x,for-loop,Python,Python 3.x,For Loop,我正在尝试为循环创建一个,但我得到了一些未经处理的输出: 我的循环示例: input1 = ['a', 'b', 'c', 'd'] input2 = ['a', 'b', 'c', 'd', 'e'] for i in range(0,4,1) for j in range(0,5,1) output = input1[i] + "-" + input2[j] print(output) 调试后会有如下一些结果: a - a b - b c - c d - d 我不
,但我得到了一些未经处理的输出:
我的循环示例:
input1 = ['a', 'b', 'c', 'd']
input2 = ['a', 'b', 'c', 'd', 'e']
for i in range(0,4,1)
for j in range(0,5,1)
output = input1[i] + "-" + input2[j]
print(output)
调试后会有如下一些结果:
a - a
b - b
c - c
d - d
我不想要它们,因为它等于零
有人能建议我怎么处理吗?只有在input1[i]
和input1[i]
不相等时才打印输出:
input1 = ['a', 'b', 'c', 'd']
input2 = ['a', 'b', 'c', 'd', 'e']
for i in range(len(input1)):
for j in range(len(input2)):
if input1[i] != input2[j]:
output = input1[i] + "-" + input2[j]
print(output)
请注意范围(1,4,1)
和范围(1,5,1)
不正确,因为列表的索引从0开始,而不是从1开始。使用range(list)
确保列表中的所有元素都被迭代
由于您仅从两个列表中读取,因此可以使用for list中的元素
语法,该语法迭代列表中的元素,并且更加简洁:
input1 = ['a', 'b', 'c', 'd']
input2 = ['a', 'b', 'c', 'd', 'e']
for i in input1:
for j in input2:
if i != j:
output = i + "-" + j
print(output)
输出:
a-b
a-c
a-d
a-e
b-a
b-c
b-d
b-e
c-a
c-b
c-d
c-e
d-a
d-b
d-c
d-e
您可以尝试使用以下示例代码排除相同的元素:
input1 = ['a', 'b', 'c', 'd']
input2 = ['a', 'b', 'c', 'd', 'e']
for i in range(1,4,1)
for j in range(1,5,1)
if input1[i] != input[j]
output = input1[i] + "-" + input2[j]
print(output)
您可以使用if
将input1[i]
与input2[j]
进行比较,并跳过一些对
if input1[i] != input2[j]:
print(input1[i] + "-" + input2[j])
你的代码确实有效,所以我更改了它
我对input1中的I使用,而不是对范围(1,4,1)
中的I使用,以使其更具可读性
input1 = ['a', 'b', 'c', 'd']
input2 = ['a', 'b', 'c', 'd', 'e']
for i in input1:
for j in input2:
if i != j:
print(i + "-" + j)
你说“我不想要它们,因为它等于零”是什么意思。而且,这不是有效的代码。请张贴实际代码。如果
,您不知道如何使用?使用if
您只能打印部分对。您好,我只想在循环之后,我将有a-b a-c a-d a-e。我不想要a-a。然后使用if
比较input1[I]
和input2[j]
并跳过对a
,a
@furas您能描述更多细节吗?谢谢您可以演示如何将用于input1中的i:
而不是用于范围内的i(len(input1))