Python check whether a list includes some value All In One

发布时间 2023-04-27 14:49:50作者: xgqfrms

Python check whether a list includes some value All In One

list includes

error

#!/usr/bin/env python3
# coding: utf8

contacts = [
  ('James', 42),
  ('Amy', 24),
  ('John', 31),
  ('Amanda', 63),
  ('Bob', 18)
]

name = input()
names = []

for tp in contacts:
  # 构造 list keys
  if tp[0] == name:
    print(tp[0] + ' is ' + tp[1])
    # You are trying to concatenate a string and an integer. ❌
    # You will need to convert the integer to a string in order to concatenate it.

# python3 ./tuple.py Amanda
# python3 ./tuple.py xgqfrms

solutions

#!/usr/bin/env python3
# coding: utf8

contacts = [
  ('James', 42),
  ('Amy', 24),
  ('John', 31),
  ('Amanda', 63),
  ('Bob', 18)
]

name = input()
names = []

for tp in contacts:
  # 构造 list keys
  if tp[0] == name:
    # 类型转换 ✅
    print(tp[0] + ' is ' + str(tp[1]))

# python3 ./tuple.py Amanda
# python3 ./tuple.py xgqfrms
#!/usr/bin/env python3
# coding: utf8

contacts = [
  ('James', 42),
  ('Amy', 24),
  ('John', 31),
  ('Amanda', 63),
  ('Bob', 18)
]

name = input()
names = []

for tp in contacts:
  # 构造 list keys
  names.append(tp[0])
  if tp[0] == name:
    # hack: print 类型分割 ✅
    print(tp[0] + ' is', tp[1])

# ✅
if name not in names:
  print("Not Found")

# python3 ./tuple.py Amanda
# python3 ./tuple.py xgqfrms
#!/usr/bin/env python3
# coding: utf8

contacts = [
  ('James', 42),
  ('Amy', 24),
  ('John', 31),
  ('Amanda', 63),
  ('Bob', 18)
]

name = input()
names = []

for tp in contacts:
  # 构造 list keys
  names.append(tp[0])
  if tp[0] == name:
    print(tp[0] + ' is', tp[1])

# ? https://flexiple.com/python/python-list-contains/
result = any(item in name for item in names)
if not result:
  print("Not Found")

# python3 ./tuple.py Amanda
# python3 ./tuple.py xgqfrms

image

demos

https://www.sololearn.com/learn/courses/python-intermediate/code-coach/912216124?returnUrl=/learn/courses/python-intermediate/lesson/912154709?p=3

(? 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

Python Tutorials

https://www.runoob.com/python3/python3-list.html

https://www.runoob.com/python3/python3-tuple.html

https://www.runoob.com/python3/python3-basic-operators.html

refs

https://flexiple.com/python/python-list-contains/

https://thispointer.com/python-how-to-check-if-an-item-exists-in-list-search-by-value-or-condition/



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 ?️,侵权必究⚠️!