如何在不使用itertools导入组合的情况下从列表中获取所有项目对

时间:2018-12-13 08:47:07

标签: python python-3.x

我有一个列表,我想要列表中所有可能的项目组合。

from itertools import combinations
l = [1,2,3]
for i in combinations(l,2):
    print(i) // (1, 2) (1,3) (2,3)

我想要相同的输出,但不使用itertools。 我尝试过:

l = [1,2,3]
for i in l:
    for j in l:
        print((i,j)) // (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)

如何在不使用itertools的情况下获得相同的输出?

3 个答案:

答案 0 :(得分:1)

也许试试这个

l = [1, 2, 3]
for i in l:
    for j in l:
        if(j <= i):
            continue
        else:
            print(i, j)

答案 1 :(得分:1)

您可以在文档中找到itertools.combinations的示例实现:

  

大致等同于:

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

答案 2 :(得分:0)

您可以在一个衬套中这样做只是为了提高效率:

[FunctionName("SomeEvent")]
public static void Run(
  [EventHubTrigger("some-hub", Connection = "EventHubConnection" )]
  EventData ev,
  ILogger log,
  ExecutionContext context,
  IConfiguration configuration,
  [EventHub("brd-iot-eventhubs", Connection = "OutputEventHubConnection")]
  ICollector<EventData> outputEvents)
  {
    var config = new ConfigurationBuilder()
   .SetBasePath(context.FunctionAppDirectory)
    .AddJsonFile(SETTINGS, optional: true, reloadOnChange: true)
    .AddEnvironmentVariables()
    .Build();

    string customername = config.GetValue<string>("Customer");
    string connectionString = config.GetConnectionString("myDatabase");
    [...]