假设我有以下元组列表:
[('test', {'key': 'testval1' }),
('test', {'key': 'testval2' }),
('test', {'key': 'testval3' }),
('test', {'key': 'testval4' }),
('foo', {'key': 'testval5' }),
('oof', {'key': 'testval6' }),
('qux', {'key': 'testval7' }),
('qux', {'key': 'testval8' })]
我想过滤并获取具有第一项“ test”字符串的第二项对象的所有值的列表。所以输出将是:
['testval1','testval2','testval3','testval4']
设法通过Output = list(filter(lambda x:'test'in x,condition))获得测试元素。但这又给了我另一个元组列表。我如何才能再次获得没有循环的第二个obj元素的值?
答案 0 :(得分:2)
>>> elements = [('test', {'key': 'testval1' }),
... ('test', {'key': 'testval2' }),
... ('test', {'key': 'testval3' }),
... ('test', {'key': 'testval4' }),
... ('foo', {'key': 'testval5' }),
... ('oof', {'key': 'testval6' }),
... ('qux', {'key': 'testval7' }),
... ('qux', {'key': 'testval8' })]
>>> [d['key'] for (s, d) in elements if s == 'test']
['testval1', 'testval2', 'testval3', 'testval4']
答案 1 :(得分:0)
使用单个理解即可做到:
[b['key'] for a, b in data if a == 'test']
(假设您的列表为data
)
答案 2 :(得分:0)
你可以做
print([*map(lambda x: x[1]['key'], filter(lambda x: x[0] == 'test' in x, a))])
列表理解是通过在列表名称后添加if来过滤此类列表的好方法。
或者您可以通过过滤器和地图来完成
print(list(map(lambda x: x[1]['key'], filter(lambda x: x[0] == 'test' in x, a))))
或
['testval1', 'testval2', 'testval3', 'testval4']
所有这些都将输出
function wmtp_gallery_block_static_function () {
global $wpdb;
$domain = 'wmtp-gallery-js';
$table_name = $wpdb->prefix . 'wmtp_gallery_block_static';
if(isset($_POST['submit'])){
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
$file = count($_FILES['upload']['name']);
$upload_dir=wp_upload_dir();
$url=$upload_dir['url'].'/'.$file;
$uploadedfile = $_FILES['upload'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
$post_data=array(
'images' => esc_url($movefile["url"])
);
$post_format=array(
'%s'
);
$wpdb->insert( $table_name, $post_data, $post_format);
}
?>
<h1>Upload The Image</h1>
<form action="" method="POST" enctype="multipart/form-data">
<label for="files">Select files:</label>
<input type="file" id="files" name="upload[]" multiple><br><br>
<input type="submit" name="submit">
</form>
<h2>All Images Are Available</h2>
<?php
$data = $wpdb->get_results($wpdb->prepare( "SELECT * FROM $table_name" ));
echo '<div class="wmtp-galeery-admin">';
foreach ($data as $img) {
if(isset($img->images)) {
echo '<img src="'.$img->images.'">';
} else {
echo '';
}
}
echo '</div>';
}
答案 3 :(得分:0)
使用Setdefault
output=[]
for item,dict in li:
if item == 'test':
var = dict.setdefault('key',{})
output.append(var)
print(output)