我应该如何连接列表的元素,以便结果是成对的元素?
How shall I concatenate the elements of a list so that the outcome is pairs of the elements?
我有一个列表 [a, b, c]。我想对列表的元素(ab、ac、bc)进行配对,但我不需要 aa、bb、cc。如果我有交流电,我也不需要 ca。
这是尝试:
list = ["a","b","c"]
x = 0
y = x + 1
while len(list) > y:
p1 = l[x]
p2 = l[y]
z = p1 + p2
print(z)
y = y + 1
while len(list) > x+1:
x = x + 1
print(z)
此代码给出了 ab、ab、cc、cc 结果。
预期结果将是:
ab
交流电
公元前。
感谢您提前提出建议。
1XY0
你可以选择 itertools.combinations
>>> import itertools
>>> [''.join(i for i in comb) for comb in itertools.combinations(['a','b','c'],2)]
['ab', 'ac', 'bc']
一点改进:
- 如果
len(l)
等于y
,设置y
为0,这样在x
时可以取到l
的第一个元素在最后一个元素。
- 如果
len(x)
等于x
,跳出循环。
- 只使用一次
print()
。在您的代码中,您使用了两次。
- 删除第二个
while
循环。没必要
l = ["a","b","c"]
x = 0
y = x + 1
while len(l) >= y:
if y==len(l):
y=0
if x == len(l):
break
p1 = l[x]
p2 = l[y]
z = p1 + p2
y += 1
x += 1
print(z)
输出:
ab
bc
ca
这是适合您的代码:
l = ["a","b","c","d"]
x = 0
y = x + 1
l1 = []
while x < len(l)-1:
l1.append(l[x]+l[y])
y += 1
if y == len(l):
x += 1
y = x+1
print (" ".join(l1))
输出:
ab ac ad bc bd cd
我有一个列表 [a, b, c]。我想对列表的元素(ab、ac、bc)进行配对,但我不需要 aa、bb、cc。如果我有交流电,我也不需要 ca。 这是尝试:
list = ["a","b","c"]
x = 0
y = x + 1
while len(list) > y:
p1 = l[x]
p2 = l[y]
z = p1 + p2
print(z)
y = y + 1
while len(list) > x+1:
x = x + 1
print(z)
此代码给出了 ab、ab、cc、cc 结果。 预期结果将是: ab 交流电 公元前。 感谢您提前提出建议。 1XY0
你可以选择 itertools.combinations
>>> import itertools
>>> [''.join(i for i in comb) for comb in itertools.combinations(['a','b','c'],2)]
['ab', 'ac', 'bc']
一点改进:
- 如果
len(l)
等于y
,设置y
为0,这样在x
时可以取到l
的第一个元素在最后一个元素。 - 如果
len(x)
等于x
,跳出循环。 - 只使用一次
print()
。在您的代码中,您使用了两次。 - 删除第二个
while
循环。没必要
l = ["a","b","c"]
x = 0
y = x + 1
while len(l) >= y:
if y==len(l):
y=0
if x == len(l):
break
p1 = l[x]
p2 = l[y]
z = p1 + p2
y += 1
x += 1
print(z)
输出:
ab
bc
ca
这是适合您的代码:
l = ["a","b","c","d"]
x = 0
y = x + 1
l1 = []
while x < len(l)-1:
l1.append(l[x]+l[y])
y += 1
if y == len(l):
x += 1
y = x+1
print (" ".join(l1))
输出:
ab ac ad bc bd cd