破烂清单的交叉点

发布于 2025-01-23 18:31:13 字数 300 浏览 1 评论 0原文

我想编写一个从用户输入中获取破烂列表的函数并找到交叉点

def intersection():
    intersect_list = []
    for i in lst[0]:
        for j in lst[1]:
            if i == j:
                intersect_list.append(i)
    return intersect_list


lst = ("enter list:")

I want to write a function that takes a ragged list from user input and find the intersection

def intersection():
    intersect_list = []
    for i in lst[0]:
        for j in lst[1]:
            if i == j:
                intersect_list.append(i)
    return intersect_list


lst = ("enter list:")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伴随着你 2025-01-30 18:31:13

来处理任意数量

from itertools import product

def intersection(ragged_list):
    return [p[0] for p in product(*ragged_list) if len(set(p)) == 1]

print(intersection([[1,2,3,4],[2,3,9,8,7,5]]))
# [2, 3]

可以使用itertools.product:如果您希望用户能够将列表作为标准的Python文字输入,则可以使用itertools.products.products.products.products.products.products.products.strands .literal_eval

from ast import literal_eval

print(intersection(literal_eval(input("Enter list: "))))
Enter list: [[1,2,3,4],[2,3,9,8,7,5]]
[2, 3]

如果您需要一个函数 输入从用户中输入列表并打印交叉点,则只需写def> def my_awesome_function():它。

from ast import literal_eval
from itertools import product

def intersection(ragged_list):
    """Returns a 1D list representing the intersection of a ragged list."""
    return [p[0] for p in product(*ragged_list) if len(set(p)) == 1]

def my_awesome_function():
    """Takes a ragged list from user input and prints the intersection."""
    print(intersection(literal_eval(input("Enter list: "))))

my_awesome_function()

Your function can be written to handle an arbitrary number of sublists by using itertools.product:

from itertools import product

def intersection(ragged_list):
    return [p[0] for p in product(*ragged_list) if len(set(p)) == 1]

print(intersection([[1,2,3,4],[2,3,9,8,7,5]]))
# [2, 3]

If you want the user to be able to input the list as a standard Python literal, you could use ast.literal_eval:

from ast import literal_eval

print(intersection(literal_eval(input("Enter list: "))))
Enter list: [[1,2,3,4],[2,3,9,8,7,5]]
[2, 3]

If you need a function that inputs the list from the user and prints the intersection, just write def my_awesome_function(): and put the code inside it.

from ast import literal_eval
from itertools import product

def intersection(ragged_list):
    """Returns a 1D list representing the intersection of a ragged list."""
    return [p[0] for p in product(*ragged_list) if len(set(p)) == 1]

def my_awesome_function():
    """Takes a ragged list from user input and prints the intersection."""
    print(intersection(literal_eval(input("Enter list: "))))

my_awesome_function()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文