编写一个接受输入列表的函数,并返回一个仅包含唯一元素的新列表(元素只应在列表中出现一次,并且元素的顺序必须保留为原始列表.).
def unique_elements (list):
new_list = []
length = len(list)
i = 0
while (length != 0):
if (list[i] != list [i + 1]):
new_list.append(list[i])
i = i + 1
length = length - 1
'''new_list = set(list)'''
return (new_list)
#Main program
n = int(input("Enter length of the list: "))
list = []
for i in range (0, n):
item = int(input("Enter only integer values: "))
list.append(item)
print ("This is your list: ", list)
result = unique_elements (list)
print (result) …Run Code Online (Sandbox Code Playgroud) 我试图遍历文本文件中的列,其中每个条目只有三个选项 A, B, and C.
我想确定不同类型的选择的数量(another text file has A, B, C, and D),但如果我用a迭代列中的每个元素100 entries并将其添加到列表中,我将对每种类型进行多次重复.例如,如果我这样做,列表可能会读取[A,A,A,B,C,C,D,D,D,B,B...],但我想删除无关的条目,只是让我的列表显示可区分的类型[A,B,C,D],无论有多少条目.
有什么想法我如何将包含许多常见元素的列表减少到只显示不同可区分元素的列表?谢谢!
期望的输出:
[A, B, C, D]
我经常需要供应商的安全公告页面上列出的 CVE 列表。有时复制起来很简单,但通常它们会与一堆文本混合在一起。
\n\n我已经有一段时间没有接触过 Python 了,所以我认为这将是一个很好的练习,可以弄清楚如何提取该信息 \xe2\x80\x93 特别是因为我一直发现自己手动执行此操作。
\n\n这是我当前的代码:
\n\n#!/usr/bin/env python3\n\n# REQUIREMENTS\n# python3\n# BeautifulSoup (pip3 install beautifulsoup)\n# python 3 certificates (Applications/Python 3.x/ Install Certificates.command) <-- this one took me forever to figure out!\n\nimport sys\nif sys.version_info[0] < 3:\n raise Exception("Use Python 3: python3 " + sys.argv[0])\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport re\n\n#specify/get the url to scrape\n#url =\'https://chromereleases.googleblog.com/2020/02/stable-channel-update-for-desktop.html\'\n#url = \'https://source.android.com/security/bulletin/2020-02-01.html\'\nurl = input("What is the URL? ") or \'https://chromereleases.googleblog.com/2020/02/stable-channel-update-for-desktop.html\'\nprint("Checking URL: " + url)\n\n# CVE regular expression\ncve_pattern = \'CVE-\\d{4}-\\d{4,7}\'\n\n# query …Run Code Online (Sandbox Code Playgroud) 嗨,我有一个以下格式的文本文件:
Sam
John
Peter
Sam
Peter
John
Run Code Online (Sandbox Code Playgroud)
我想从文件中使用REGULAR EXPRESSION提取唯一记录,例如:
Sam
John
Peter
Run Code Online (Sandbox Code Playgroud)
请帮帮我.
我的问题是让用户一次输入一个世界,看看用户知道多少个独特的世界(重复的单词不算数),例如
Word: Chat
Word: Chien
Word: Chat
Word: Escargot
Word:
You know 3 unique word(s)!
Run Code Online (Sandbox Code Playgroud)
以下是我现在所拥有的:
count = 0
listword = []
word = input("Word: ")
while word != "":
for i in listword:
if i != word:
listword.append(word)
count += 1
word = input("Word: ")
print("You know "+count+"unique word(s)!")
Run Code Online (Sandbox Code Playgroud)
但是输出是这样的:
Word: hello
Word: hi
Word: hat
Word:
You know 0 unique word(s)!
Run Code Online (Sandbox Code Playgroud)
如何调整我的代码,为什么计数仍然 =0?
我有一个包含数字和名字的清单.
lst = ['new car', '232', 'famous bike','232', 'new car', '232plane', 'new car', 'plane232']
Run Code Online (Sandbox Code Playgroud)
我只想new car, famous bike数字而不是数字或字母数字.
输出将是2,因为有两个独特的单词:汽车,自行车.
我知道有一个简单的答案,但我无法理解它.
谢谢.