所以为了我的代码工作,我需要能够在for循环中放置一个for循环。对于我的项目,我试图找到所有以字母表中的字母开头的单词。我没有提出如何存储数据所以请批评我,因为我稍后会这样做。继承我的代码
$json = $res->getBody();
$array = json_decode($json);
dump($array);
答案 0 :(得分:1)
如果您希望列表中的所有单词都是字母表中的第一个字母:
wordfile = open('/usr/share/dict/words','r')
words = wordfile.read()
wordlist = words.split()
alphabet=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
alphabet_words = []
for word in wordlist:
if word[0] in alphabet:
alphabet_words.append(word)
无论如何,你可以使用comprehension lists允许你在这个格式的相同代码下面内联简单循环:
wordfile = open('/usr/share/dict/words','r')
words = wordfile.read()
wordlist = words.split()
alphabet=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
alphabet_words = [word for word in wordlist if word[0] in alphabet]
答案 1 :(得分:0)