如何通过python中的用户输入从列表中删除元素?

时间:2014-01-31 12:25:13

标签: python list for-loop user-input

我想通过使用用户输入和for循环从列表中删除元素。

这是我得到的:

patientname = input("Enter the name of the patient: ") 
for x in speclistpatient_peter:                
    del speclistpatient_peter

5 个答案:

答案 0 :(得分:4)

只需使用remove方法列表:

 l = ["ab", "bc", "ef"]
 l.remove("bc")

"bc"删除元素l

答案 1 :(得分:1)

使用列表理解;更改for循环中的列表,而循环可能会导致问题,因为列表大小更改并且索引向上移动:

speclistpatient_peter = [x for x in speclistpatient_peter if x != patientname]

这会重建列表,但会遗漏与输入的patientname值匹配的元素。

答案 2 :(得分:0)

此行不正确:

curl -vk https://xuzhao06.b...corp.com
* Rebuilt URL to: https://xuzhao06.b...corp.com/
*   Trying 10.240.189.179...
* TCP_NODELAY set
* Connected to xuzhao06.b...corp.com (10.240.189.179) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/pki/tls/certs/ca-bundle.crt
  CApath: none
* TLSv1.2 (OUT), TLS header, Certificate Status (22):
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.0 (IN), TLS handshake, Server hello (2):
* TLSv1.0 (IN), TLS handshake, Certificate (11):
* TLSv1.0 (IN), TLS handshake, Server finished (14):
* TLSv1.0 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.0 (OUT), TLS change cipher, Client hello (1):
* TLSv1.0 (OUT), TLS handshake, Finished (20):
* TLSv1.0 (IN), TLS change cipher, Client hello (1):
* TLSv1.0 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.0 / DES-CBC3-SHA
* ALPN, server did not agree to a protocol
* Server certificate:
*  subject: C=US; ST=CA; ... CN=Self-Signed Certificate for ohs1 
*  start date: Dec 24 12:36:21 2015 GMT
*  expire date: Dec 11 12:36:21 2065 GMT
* SSL: certificate subject name 'Self-Signed Certificate for ohs1 ' does not match target host name 'xuzhao06.b...corp.com'
* Closing connection 0
* TLSv1.0 (OUT), TLS alert, Client hello (1):
curl: (51) SSL: certificate subject name 'Self-Signed Certificate for ohs1 ' does not match target host name 'xuzhao06.b...corp.com'

patientname = input("Enter the name of the patient: ") 函数中放置任何内容,而不是要从列表中删除或查找的特定内容,都会导致错误。在您的情况下,您添加了input(),因此在执行后,它将在列表中搜索<​​strong>“输入患者姓名:” ,但不在此处。

在这里,您可以从列表中删除特定项目。您没有use循环,而是可以使用("Enter the name of the patient: ")函数将其删除:

remove()

答案 3 :(得分:0)

print("Enter the item you want to delete")
patientname = input() # Dont Put anything between the first bracket while using input()
speclistpatient_peter.remove(patientname)
print(speclistpatient_peter)

答案 4 :(得分:0)

要删除某个元素: speclstpatient_peter.remove('name')


如果数组包含2x相同的元素,而您只希望firstm,则它将不起作用。最动态的只是一个计数器,而不是一个指针:

x=0
while x<len(speclistpatient_peter):
    if speclistpatient_peter[x].find(something):   # or any if statement  
         del(speclistpatien_peter[x])
    else:
         x=x+1

或使函数保持可读性:

def erase(text, filter):
    return [n for n in text if n.find(filter)<0] 

a = ['bart', 'jan']
print erase(a, 'rt')