根据部分匹配python删除重复项

发布于 2025-02-01 19:03:34 字数 407 浏览 3 评论 0原文

说我有一个列表,

var1 = ["VenueA/2003", "VenueA/2006", "VenueA/2009","VenueB/2009"]

我想做的是根据VENUEX删除列表中的所有重复元素,并保留第一次出现 在上面的示例中,有三个类似的venueavenuea/2003venuea/2006venuea/venuea/2009。由于venuea/2003是第一次出现,我想保留并删除

我想要的结果是

var1 = ["VenueA/2003","VenueB/2009"]

我该怎么做?

Say I have a list

var1 = ["VenueA/2003", "VenueA/2006", "VenueA/2009","VenueB/2009"]

What I want to do is remove all duplicate elements in the list based on the VenueX and keep the first occurrence
In the above example, there are three similar VenueA which are VenueA/2003, VenueA/2006 and VenueA/2009. As VenueA/2003 is the first occurrence, I want to keep that and remove the rest of VenueA

The result that I want is

var1 = ["VenueA/2003","VenueB/2009"]

How do I go about doing that?

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

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

发布评论

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

评论(2

べ映画 2025-02-08 19:03:34

您可以构建一个由前缀键入的地图,并具有值,其中一个具有此前缀的字符串。 地图构造函数可用于此。

由于映射构造函数将保留具有给定前缀的字符串的最后一个 em> constrorce,因此您应该逆转输入和输出,以获得 first 匹配:

const arr = ["VenueA/2003", "VenueA/2006", "VenueA/2009","VenueB/2009"];

const map = new Map(arr.map(s => [s.split("/")[0], s]).reverse());
const result = [...map.values()].reverse();

console.log(result);

You can build a map keyed by the prefixes, and with as value, one of the strings that has this prefix. The Map constructor can be used for this.

As the Map constructor will retain the last occurrence of the string that has a given prefix, you should reverse the input and the output to get the first match instead:

const arr = ["VenueA/2003", "VenueA/2006", "VenueA/2009","VenueB/2009"];

const map = new Map(arr.map(s => [s.split("/")[0], s]).reverse());
const result = [...map.values()].reverse();

console.log(result);

独行侠 2025-02-08 19:03:34
k=[]
for x in var1:
  if x.startswith('VenueA') and len(k)==0:
    k.append(x)
  if x.startswith('VenueB') and len(k)==1:
    k.append(x)

#output
['VenueA/2003', 'VenueB/2009']

同样,如果您有更多场地,则可以增加LEN的价值并将其附加到k

k=[]
for x in var1:
  if x.startswith('VenueA') and len(k)==0:
    k.append(x)
  if x.startswith('VenueB') and len(k)==1:
    k.append(x)

#output
['VenueA/2003', 'VenueB/2009']

Similarly, if you have more Venues you can increase the value of len and append them to k

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