将由逗号分隔的3个数值拆分为3个不同的配对。

huangapple go评论51阅读模式
英文:

split 3 values seperated by commas into 3 different pairs

问题

Sure, here is the translated code:

我想将用逗号分隔的3个值

    a = 'a,b,c'

拆分成3对不同的值:

    (a,b), (b,c), (a,c)

我该如何在Python中实现这个目标

我尝试了

    n = [(x) for x in a.split(',')]
    x = list(zip(n[1::], n[0::2]))

但我只得到了一对: `('a', 'b')`
英文:

I'd like to split 3 values separated by commas

a = 'a,b,c'

into 3 different pairs:

(a,b), (b,c), (a,c)

How would I be able to do this on Python?

I have tried

n = [(x) for x in a.split(',')]
x = list(zip(n[1::], n[0::2]))

I get one pair: ('a', 'b')

答案1

得分: 2

以下是翻译好的部分:

尝试使用itertools中的combinations

from itertools import combinations
a = 'a,b,c'
a = a.split(",")
for group in combinations(a,2):
    print(group)

输出:

('a', 'b')
('a', 'c')
('b', 'c')
英文:

Try using combinations from itertools:

from itertools import combinations
a = 'a,b,c'
a = a.split(",")
for group in combinations(a,2):
    print(group)

Output:

('a', 'b')
('a', 'c')
('b', 'c')

答案2

得分: 1

Sure, here's the translated content:

如果您愿意使用库,您可以使用itertools中的combinationsItertools文档

在这种情况下,它将非常简单:

from itertools import combinations

csv='a,b,c'
combinations(csv.split(','),2)

# [('a', 'b'), ('a', 'c'), ('b', 'c')]

Bibhav比我提前发布了答案,尽管他们的答案使用排列允许重复,例如'('a','b'),('b','a')',而组合则不允许。根据您的用例,可以选择哪种方法。

英文:

If you're open to using libraries, you can use combinations from itertools. Itertools documentation

In this case, it would be as simple as:

from itertools import combinations

csv='a,b,c'
combinations(csv.split(','),2)

#[('a', 'b'), ('a', 'c'), ('b', 'c')]

Bibhav beat me to posting, though their answer with permutations allows duplications, e.g. '('a','b'),('b','a') whereas combinations does not. Up to your use case which is preferred.

答案3

得分: 0

I am not sure what the logic is behind grouping these pairs together:

(a,b), (b,c), (a,c)

However, if you wanted to group each element with every other element you can use this:

a = 'a,b,c'
my_list = a.split(',')
new_list = []
for i in my_list:
    for j in my_list:
        if i != j:
            new_list.append((i,j))

And you will get

[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
英文:

I am not sure what the logic is behind grouping these pairs together:

(a,b), (b,c), (a,c)

However, if you wanted to group each element with every other element you can use this:

a = 'a,b,c'
my_list = a.split(',')
new_list = []
for i in my_list:
    for j in my_list:
        if i != j:
            new_list.append((i,j))

And you will get

[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]

huangapple
  • 本文由 发表于 2023年4月13日 18:03:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76004162.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定