python - 如何从使用函数创建的列表中选择特定字符

标签 python python-3.x list function indexing

我想知道是否可以索引列表,如果这样的列表是使用函数制作的。

例如,使用下面给出的代码,如何打印出我使用该函数生成的列表中的第一个(或第二个或第三个等)字符?

这是我的代码:

import random
a="abcdefghijklmnopqrstuvwxyz"
def password(k):
  x=[]
  for n in range(k):
    x.append(random.choice(a))
  print(x)

password(6)

我想对这个问题再补充一点,因为我知道如何在函数中一个一个地打印字符,但这并不是我要找的,我想做的是比较两个列表由函数创建。

例如:

list1 = ['a','g','e','z','p','a']
list2 = ['l','g','t','h','a','f']

如果我们假设我使用该函数生成了这两个包含 6 个字符的列表,是否可以通过这种方式比较它们,我实际上可以确定与两个列表的相同索引一致的字母是 g(第二个字母)?

最佳答案

list1 = ['a','g','e','z','p','a']
list2 = ['l','g','t','h','a','f']

common_positions = [i for i in range(len(list1)) if list1[i] == list2[i]]
common_chars = [list1[i] for i in common_positions]

print(common_positions)
print(common_chars)

输出:

[1]
['g']

现在,如果您只想要第一个重合的字母:

if common_chars:              # Test whereas this list is not empty
    print(common_chars[0])

输出:

g

关于python - 如何从使用函数创建的列表中选择特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51805272/

相关文章:

Python - 从文本文件调用行来编译第二个文件的模式搜索

删除包含特定字符串的整个列表元素

python - 给定一组字母,如何创建一个单词与这些字母的所有可能组合,并用指定的数字重复?

python - 如何在 tensorflow 中更新张量内的子张量?

python - 与 Python 套接字服务器通信(Chrome 扩展)

Python包: Get the country based on adress(non-ip)

Python3 使用 lambda 对嵌套字典的列表进行排序

python - ggplot2 不存在于 python 的 rpy2 中?

Python 在 for 循环中拆分为多个对(名称 :value) of output

java - 避免多次调用到底是什么意思?